2013. 5. 6. 11:39ㆍ프로그래밍/C/C++
//n명 중에서 생일이 같은 사람이 몇명? _ birthday paradox
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, j, k, detect, cnt, p[400]; //i,j,k:반복변수 detect:detect변수 cnt:cnt변수 p[400]:400명까지 생일 저장하는 배열
int pCnt,iCnt; //pCnt:사람수 iCnt:표본실험횟수
srand((unsigned int)time(0));
//주어진 배열의 크기와 마이너스 값을 입력받지 않도록 do while문을 사용
do{
scanf("%d %d", &pCnt, &iCnt);
}while(pCnt <= 0 || pCnt > 400 || iCnt <= 0);
cnt=0; //cnt를 0으로 초기화
//표본실험 횟수만큼 반복
for(j=0 ; j<iCnt ; j++)
{
//사람수 만큼 생일을 랜덤하게 지정
for(i=0 ; i<pCnt ; i++)
{
p[i]=rand()%365;
}
detect = 0;
//생일이 같은지 한명씩 반복문을 돌면서 비교
for(i=0 ; i<pCnt ; i++)
{
for(k=i+1 ; k<pCnt ; k++)
{
if(p[i] == p[k])
{
detect = 1; //생일이 같을 경우 detect를 1로 둔다.
}
}
}
if(detect)
{
cnt++; //detect변수가 true인 경우 cnt를 증가시켜 준다.
}
}
printf("%5.2lf%%\n", (double)cnt/iCnt*100); //전체 cnt횟수를 표본실험횟수만큼 나누어준값으로 확률을 계산
//printf("%5.2lf%%\n", (double)cnt/(j+1)*100);
return 0;
}
/*
#define n 100
int main()
{
int i, j, detect, p[n], cnt=0;
srand((unsigned)time(0));
for(i=0 ; i<n ; i++)
{
p[i] = rand()%365;
}
for(i=0 ; i<n ; i++)
{
detect = 0;
for(j=i+1 ; j<n ; j++)
{
if(p[i] == p[j])
{
detect = 1;
}
}
if(detect)
{
cnt++;
}
}
printf("생일이 같을 확률 : %.2lf\n", (double)cnt/n);
return 0;
}
*/
'프로그래밍 > C/C++' 카테고리의 다른 글
[논리적 사유연습]윷을 던졌을 때의 확률 구하기 (0) | 2013.05.13 |
---|---|
[논리적 사유연습]PuzzleStrike(숫자야구게임) (0) | 2013.05.08 |
[MFC]프로젝트 생성 후 메뉴 툴바 제거 (0) | 2013.04.30 |
[논리적 사유연습]동전을 N번 던졌을 때 앞면이 나올 확률 (0) | 2013.04.29 |
[논리적 사유연습]랜덤변수 생성(N까지의 정수, 실수) (0) | 2013.04.22 |