【问题标题】:Issues with rand and srandrand 和 srand 的问题
【发布时间】:2021-01-23 22:36:02
【问题描述】:

我正在编写一个程序来获得 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;
}

有人知道发生了什么吗?

【问题讨论】:

标签: c++ random srand


【解决方案1】:

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

while (roll != 6) {
   ...
}

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

要解决此问题,您可以

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

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多