gpt4 book ai didi

C++ 生日概率

转载 作者:行者123 更新时间:2023-11-28 06:11:45 25 4
gpt4 key购买 nike

我正在尝试自学 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com