rand 和 srand 的问题

Nic*_*ico 0 c++ random 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;
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道发生了什么?

tem*_*def 5

请注意,roll仅在此循环内更新:

while (roll != 6) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

这意味着在roll设置为 6 的循环结束运行后,它将永远不会再次运行,即使外循环再次执行。

要解决此问题,您可以

  1. 将此更改为do ... while循环,以便它始终至少执行一次;或者
  2. roll在通过外while循环的每次迭代中手动重置为 6 以外的值;或者
  3. 更改 whereroll的定义,使其位于外while循环的本地,因此每次外循环迭代都会获得它的新副本,这基本上是选项 (2) 的更好版本。