0

我必须做生日悖论计划作为学校的作业。我让程序运行,但似乎无法获得正确的答案。我认为这是我在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
    }
}
4

2 回答 2

0

main()中,变量count没有被初始化,它被传递给check_birthdays(),所以结果可以是任何东西。

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

于 2013-02-19T13:47:27.127 回答
0

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

再提示一下,不用srand()每次都打电话。

于 2013-02-19T11:04:56.360 回答