【问题标题】:How to do the Birthday Paradox looping如何进行生日悖论循环
【发布时间】: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


【解决方案1】:

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

再提示,不用每次都打srand()

【讨论】:

  • “不需要”低估了这个问题。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多