소프트웨어/C++

[2004년 중간 7번] 난수 발생 - rand()

카켈 2007. 2. 27. 22:53




목적
  - 특정 범위의 난수를 만들줄 안다.

문제


코드
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(void)
{
 srand((unsigned)time(NULL));
 rand();

 double afRand[30] = {0.0};
 double dTotal = 0.0;
 int i = 0;
 

 cout << "생성된 난수 : " << endl;
 while (i < 30)
 {
  afRand[i] = ((rand() % 2000) - 1000) / 1000.0;
  cout << afRand[i] << '\t';
  dTotal += (afRand[i] * afRand[i]);

  i++;
 }

 cout << endl << "난수의 제곱 합 : " << dTotal << endl;

 return 0;
}
해설
  - 원하는 범위의 난수를 만드는 방법은 (rand() % 원하는 값의 0 을 기준으로 최대값 - +- 중간값) / 자릿수의 역수
  - 마지막에 1000.0 으로 하지 않으면 int 형 나눗셈이 되어 버려서 int 형으로 전환 소숫점이 삭제되어 0이 출력됩니다.

참고
  - 유사 문제