数学模型:
我们只考虑平年的生日,一年365天,1表示1月1日生日的人,2表示1月2日生日的人,32表示2月1日生日的人。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main()
{
int test = 0;//统计已经进行的实验次数
int count = 0;//统计有同一天生日的单次实验的数量。
for(;test<=999;test++)
{
printf("——————————————第%d次实验开始!——————————\n",test+1);
sleep(1);
int i=0;
int class_[60] = {0};
int birth[365] = {0};
srand((unsigned)time(NULL));
for(i=0;i<=59;i++)
{
int rand_ = rand()%365;
birth[rand_] += 1;
if(birth[rand_] > 1){
printf("第%d天的生日是重复的\n",rand_);
count++;
break;
}
}
}
printf("\n共计有%d次成功的实验\n",count);
return 0;
}
注意:
在上文中,我们使用了桶排序的想法来标记生日。即数组birth起初365个int全部为0,每随机生成的0-364其中一个数字,我们把对应得birth++。
sleep函数是必须的。因为srand使用了系统时间作为种子,如果不试图暂停程序,那么会发现rand得到的数字是完全一样的。