소프트웨어/C++

[2005년 중간 4번] 난수 확률 생성 - 난수 생성

카켈 2007. 3. 6. 04:33




목적
  -  특정 범위의 단위 정수 난수를 생성할줄 안다.

문제

코드

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
 int i50, i60, i70, i80, i90, i, iRand;
 i50 = i60 = i70 = i80 = i90 = i = iRand = 0;

 srand((unsigned)time(0));
 rand();

 cout << "생성된 난수 :" << endl;

 while( i < 100)
 {
  iRand = rand() % 5;
  switch(iRand)
  {
   case 0:
    i50++;
    break;

   case 1:
    i60++;
    break;

   case 2:
    i70++;
    break;

   case 3:
    i80++;
    break;

   case 4:
    i90++;
    break;

   default:
    break;

  }

  cout << (iRand + 5) * 10 << "  ";
  i++;

 }

 cout << "50이 생성될 확률 : " << i50 << endl
  << "60이 생성될 확률 : " << i60 << endl
  << "70이 생성될 확률 : " << i70 << endl
  << "80이 생성될 확률 : " << i80 << endl
  << "90이 생성될 확률 : " << i90 << endl;

 return 0;
}

해설
  - 예전 문제에서 범위만 바꾸어서 나온 것입니다. 0부터 시작하는 정수에서 확률을 계산해도 결과는 같다는 것을 이용했습니다.

참고
  - 유사 문제