如何做生日悖论循环
问题描述:
我必须做生日悖论计划作为学校的任务。我得到程序运行,但似乎有麻烦得到正确的答案。我认为这是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
}
}
答
不知道用“它不工作”你的意思,我猜你可能想用一些无效值替换匹配的生日,这样它会当你在循环中前进时,不会再次匹配。
还有一个提示,每次都不需要拨打srand()
。
+0
“不需要”而是低估了这个问题。 – 2013-02-19 12:08:00
答
在main()
中,变量count
未初始化并且传递给check_birthdays()
,所以结果可以是任何值。
另外,在C++中当数组的大小在运行时决定时,正常的解决方案是使用std::vector
。
@Phillipp:家庭作业标签[已弃用](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) – Default 2013-02-19 11:03:29
您期待什么答案?可能我建议你从已知的输入开始,而不是随机的,这样你可以在测试“真实”数据之前微调你的算法(这也使得它更易于调试) – Default 2013-02-19 11:12:28
只在一开始就调用'srand'该程序。 – 2013-02-19 12:07:06