【发布时间】:2013-02-19 10:59:55
【问题描述】:
我必须将生日悖论计划作为学校的作业。我让程序运行,但似乎无法获得正确的答案。我认为这是我在check_birthdays 函数中的循环的问题。
代码如下:
#include <iostream>
using namespace std;
#include<time.h>
void check_birthdays (int birthdays[], int num, int count=0)
{
for (int i=0; i<num; i++) //to check each person in the group
{
for (int j=i+1; j<num; j++) //against every other person in the group
{
if (birthdays[i]==birthdays[j])
count++;
}
}
//print out the number of people with ame birthday
cout<<"The number of people who share their birthday is "<<count;
}
int main()
{
//create a variable for an inputted number of people
int people, count;
cout<< "Please input a number of people: "<<endl;;
cin>>people;
int birthdays[people];
//input check
if (people<50 || people>100)
cout<<"Error, please try again.";
else
{ //fill that array with random numbers
for (int i=0; i<people; i++)
{
srand (time (NULL));
birthdays[i]= rand()%365;
}
check_birthdays (birthdays, people, count); //send to the next function
}
}
【问题讨论】:
-
@Phillipp:作业标签是deprecated
-
您期待什么答案?我是否建议您从已知输入而不是随机输入开始,这样您就可以在测试“真实”数据之前微调您的算法(这也更容易调试)
-
在程序开始时只调用一次
srand。
标签: c++ loops for-loop birthday-paradox