[英]Issues with rand and srand
我正在制作一个程序来获得平均掷骰子数以获得 6,但 RNG 似乎存在问题。 我怀疑这是种子,因为每次编译和运行代码时数字都不同,但每次尝试都不会改变,因此平均值不会改变。 这是我的代码:
#include <iostream>
#include <cstdlib> // random numbers header file//
#include <ctime> // used to get date and time information
using namespace std;
int main()
{
int roll = 0; //declare a variable to keep store the random number
int i = 0;
int counter = 0;
int resume = 1;
int average = 0;
int totalrolls = 0;
srand(time(0)); //initialise random num generator using time
while (resume != 0) {
while (roll != 6) {
roll = rand() % 6 + 1; // generate a random number between 1 and 6
i++;
}
counter++;
totalrolls += i;
average = totalrolls / counter;
cout << "the average number of rolls to get a 6 is " << average << ", based on " << counter << " sixes." << endl;
cout << "do you wish to keep rolling? ";
cin >> resume;
cout << endl;
}
return 0;
}
任何人都知道发生了什么?
请注意, roll
仅在此循环内更新:
while (roll != 6) {
...
}
这意味着该循环在roll
设置为 6 的情况下完成运行后,它将永远不会再次运行,即使外循环再执行一次。
要解决此问题,您可以
do ... while
循环,以便它始终至少执行一次; 或者while
循环的每次迭代中手动将roll
重置为 6 以外的值; 或者roll
位置,使其位于外部while
循环的本地,因此每次外部循环迭代都会获得它的新副本,这基本上是选项 (2) 的更好版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.