如何做生日悖论循环

时间:2013-02-19 10:59:55

标签: c++ loops for-loop birthday-paradox

我必须做生日悖论计划作为学校的任务。我得到了程序运行,但似乎很难得到正确的答案。我认为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
    }
}

2 个答案:

答案 0 :(得分:0)

在不知道你的意思“它不起作用”的情况下,我猜你可能想用一些无效的值替换匹配的生日,这样当你在循环中前进时它就不会再次匹配。 / p>

还有一个提示,每次都不需要拨打srand()

答案 1 :(得分:0)

main()中,变量count未初始化并传递给check_birthdays(),因此结果可以是任何内容。

此外,在C ++中,当在运行时决定数组的大小时,通常的解决方案是使用std::vector