소프트웨어/C++
[2004년 기말 13번] 난수 확률 - 특정 범위 난수 출력
카켈
2007. 3. 5. 01:20
목적
- 난수를 만들고 생성 확률을 계산한다.
문제
코드
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(void)
{
srand((unsigned)time(0));
rand();
int iRand, i10, i20, i30, i40, i50, i;
iRand = i10 = i20 = i30 = i40 = i50 = i = 0;
while(i <= 100)
{
iRand = rand() % 5 + 1;
switch(iRand)
{
case 1:
i10++;
break;
case 2:
i20++;
break;
case 3:
i30++;
break;
case 4:
i40++;
break;
case 5:
i50++;
break;
default:
break;
}
cout << iRand * 10 << " ";
i++;
}
cout << endl << endl << "10이 나올 확률 : " << i10 / 100.0 << endl;
cout << "20이 나올 확률 : " << i20 / 100.0 << endl;
cout << "30이 나올 확률 : " << i30 / 100.0 << endl;
cout << "40이 나올 확률 : " << i40 / 100.0 << endl;
cout << "50이 나올 확률 : " << i50 / 100.0 << endl;
return 0;
}
- rand() % 5 을 통해 0 부터 4까지 + 1 을 통해 1 부터 6까지 출력합니다.
- switch-case 문으로 확률을 더하고 출력은 10배를 하여 원하는 값을 만들어 냅니다.
- 10 ~ 50 가 10의 단위로 나올 확률과 1 ~ 5 가 나올 확률은 동일합니다.
참고
- 유사 문제