C++ 生日概率

标签 c++

我正在尝试自学 C++,为今年秋天的研究生院做准备,但我在解决这个生日悖论问题时遇到了一些麻烦。我的代码似乎运行正常,但我没有得到正确的输出。如果有人有任何建议,请告诉我。

 #include <cstdlib>
 #include <iostream>
 #include <ctime>

 using namespace std;

int main()
{
    srand(time(NULL));

    const int trials = 100000;
    int birthdays[50];
    int numMatches;


    for(int i = 2; i <= 50; i++)
    {
        numMatches = 0;

        for(int j = 1; j <= trials; j++)
        {

            for(int k = 1; k <= i; k++)
            {
                birthdays[k] = (rand() % 365) + 1;
            }

            int m = 1;
            bool matched = false;
            while(m < i && !matched){
                int n = m + 1;

            while(n <= i && !matched){
                if(birthdays[m] == birthdays[n]){
                    numMatches++;
                    matched = true;
                }
                n++;
            }
                m++;
            }
        }

        cout << "Probability of " << i << " people in a room sharing a birthday is \t"
          << ( float(numMatches) / float(trials) ) << endl;
    }  
}

最佳答案

您的代码没有计算一个 50 人的房间里有两个人同一天生日的概率。有几个错误,主要是索引,但这是最大的问题:

for(int j = 1; j <= trials; j++) {
    // assigns a random birthday to the first i people (should be 0 indexed)
    for(k = 1; k <= i; k++)
        birthdays[k] = (rand() % 365) + 1;
    // Does *exactly* the same thing as the previous loop, overwriting what
    // the initial loop did. Useless code
    for(m = 1; m <= i; m++)
        birthdays[m] = (rand() % 365) + 1;
    // At this point, m = k = i + 1. Here you check if
    // the i + 1st array value has the same b-day. It will, because they're
    // the same thing. Note you never set the i + 1st value so the loops
    // above did nothing
    if(birthdays[k] == birthdays[m])
        ++numMatches;
}

所以你在这里得到的是这样的:

  • 执行以下 48 次迭代(从第一个循环开始,从 2 到 50:不知道这些值从何而来)
    • 对于这 48 次迭代中的每一次,执行 10k 次迭代:
      • 将一堆随机的东西分配给一个覆盖东西的数组
      • 忽略您在数组中写入的值,进行始终为真的比较并将 numMatches 递增 1

关于C++ 生日概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127932/

相关文章:

c++ - 引用类型之间的隐式转换

c++ - 在 DLL 中调用非导出函数

c++ - 如何在 OpenCV 图像分析中跳过掩码

c++ - 是否可以返回不可移动、不可复制类型的实例?

c++ - 使用指向基类的指针访问 protected 继承成员

c++ - 反转字符数组

c++ - 如何用 cout 打印函数指针?

c++ - 为 "external use"指定任意类类型的字段

c++ - 在 C++ 中处理大数

c++ - 将 unicode 字符串定义为字节数组