gpt4 book ai didi

c++ - 计算 rng 总数时出现意外结果

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

我编写了一个简单的程序来模拟掷 4 面骰子并计算每个数字出现的次数,这样我就可以看到 rand() 的随机性。当我简单地打印结果时,出现的唯一数字是预期的数字 1->4。当我进行计数时,我注意到在 1000 次迭代中,我最终只得到 1 到 4 之间的约 700 个刻度。为什么会这样?我觉得答案应该很明显,因为循环按预期运行,但是当我查看代码的可疑问题区域时,我看不出问题出在哪里。

int d4()
{
int x;
x = rand() % 4 + 1;
return x;
}


int main()
{
int n1 = 0;
int n2 = 0;
int n3 = 0;
int n4 = 0;
int n5 = 0;
srand(time(0));
int x = 0;
while (x <= 100)
{

std::cout << d4() << " ";
++x;

/* ++x;
if (d4() == 1)
++n1;
else if (d4() == 2)
++n2;
else if (d4() == 3)
++n3;
else if (d4() == 4)
++n4;
else
++n5; */
}

std::cout << "Number 1 was rolled " << n1 << " times." << std::endl;
std::cout << "Number 2 was rolled " << n2 << " times." << std::endl;
std::cout << "Number 3 was rolled " << n3 << " times." << std::endl;
std::cout << "Number 4 was rolled " << n4 << " times." << std::endl;
std::cout << "Somehow some other number was rolled on a 4 sided die " << n5 << " times.";

std::cin.ignore();
std::cin.clear();
std::cin.get();

return 0;
}

注意:我已经注释掉了计数片段以手动查看结果。

最佳答案

正如其他人在评论中指出的那样,您的问题是每次调用 d4() 时,它都会在 14< 之间返回不同的结果(包括)。这可能意味着在您的循环中,d4() 的返回值永远不会等于比较时的比较值。考虑:

    if (d4() == 1) // call d4(), which returns 2
++n1;
else if (d4() == 2) // call d4() again, which returns 3
++n2;
else if (d4() == 3) // call d4() again, which returns 1
++n3;
else if (d4() == 4) // call d4() again, which returns 2
++n4;
else
++n5; // No other comparison worked, so this is incremented instead.

这里的解决方案是只调用一次d4()并将它的值保存在一个变量中。

// Retrieve the random number this loop iteration and store its value
int randomNumber = d4();
std::cout << randomNumber << std::endl;

if (randomNumber == 1)
++n1;
else if (randomNumber == 2)
++n2;
else if (randomNumber == 3)
++n3;
else if (randomNumber == 4)
++n4;
else
++n5;

关于c++ - 计算 rng 总数时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674201/

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