【问题标题】:2nd call of srand() in the same program with the same seed is NOT producing the same values for successive rand()在具有相同种子的同一程序中第二次调用 srand() 不会为连续的 rand() 产生相同的值
【发布时间】:2014-04-03 22:37:33
【问题描述】:

我正在为我的 C++ 课程介绍编写一个简单的“附加问题”程序。我的讲师使用测试驱动程序对我们的代码进行评分。测试驱动程序首先使用他的代码运行程序,然后运行我的函数并比较两者。

在这段代码中,我们应该生成随机数给用户简单的加法问题。他们输入答案,程序会记录他们答对了多少,并将正确答案的数量返回给主函数。

据我了解,如果种子相同,srand() 将生成相同的数字列表。我遇到的问题是,即使我将 srand(seed) 放在函数的顶部,每个 rand() 调用生成的连续数字仍然不同。据我了解,如果您使用相同的种子回忆 srand,它将重置数字生成器并为您提供来自 rand() 的相同数字链。

因为他使用测试驱动器来评分,驱动器告诉我几乎所有的结果都是错误的,但这是因为驱动器实际上并没有计算我的随机生成的数字,它只是寻找与他得到的相同的答案在他的程序版本中。所以问题是由于某种原因调用 srand(seed) 没有使用相同的数字。

这可能是他的驱动程序的问题,如果它向我的种子函数发送的数字与他使用的不同,但也可能是我将 srand() 放在错误的位置,或者我没有使用正确。

鉴于种子值相同,谁能确认我的代码中使用 srand(seed) 是否会重置并使用相同的数字?

这是我的功能:

int correct = 0;  // initialize global variable to return correct answers
// define the additionQuestions function.

int additionQuestions(int largest, int problemCount, int seed)
{
    srand(seed);  // initialize the random generator to the same seed used in test driver
    int gen1, gen2, answer;
    bool quitting = false;

    // generate problems
for (int count = 0; count < problemCount && (!(quitting)); count++)
{
    gen1 = rand() % largest;
    gen2 = rand() % largest;

    cout << "How much is " << gen1 << " plus " << gen2 << "? ";
    cin >> answer;
    if (answer == -1)  // check for sentinel of -1
    {
        cout << endl << "  You entered -1; exiting...";
        quitting = true;

    }
    else  // check if the user's answer is correct.
    {
        cout << endl << "  You said " << gen1 << "+ " << gen2 << " = " << answer << ".";
        if (answer == gen1 + gen2)
        {
            cout << " Very good!" << endl;
            correct += 1;
        }
        else
        {
            cout << " No. Sorry, the correct answer is " << gen1 + gen2 << "." << endl;
        }
    }
} // end of for loop.
return correct;  // return the number of correct answers to the main function
}

【问题讨论】:

  • 您能否显示从'additionQuestion(..., 5)' 和'additionQuestion(..., 5)' 打印出来的前几行以显示生成的数字列表不同?
  • 您的代码实际上看起来是正确的。我希望错误在于试驾程序如何为您提供种子。
  • @jcyost 这让我产生了制作自己的 main 函数的想法,该函数调用了我的函数的两个副本并进行了比较,因此 srand(seed) 在程序中被使用了两次。第二个函数实际上给出了相同的数字,所以看起来 srand(seed) 正在正常工作。正如 ojblass 指出的那样,我想问题一定出在测试驱动程序中。是时候给我的导师发电子邮件了。谢谢大家。

标签: c++ random srand


【解决方案1】:

在你写信给你的教授之前...... 您使用从 'int seed' 到 'srand(unsigned int seed)' 的隐式类型转换,当测试驱动程序尝试使用大于 ~2.1M 的种子测试您的程序时,这可能会导致问题。

祝你好运。

【讨论】:

  • 如果是这样,我的测试程序也会被破坏吗?我在测试程序中使用的种子值是 31451256132987124987。这个种子值被提供给我的两个相互复制的函数,它仍然可以正常工作。
  • 其实我的逻辑是倒退的,不好意思。只要它是积极的,问题就不会将大量数字传递给 srand 。问题是,如果测试您的库的驱动程序将无符号整数作为种子传递。然后在传入种子时进行转换。我们是提供给您的函数的变量类型吗?
  • 是的,他说我们的函数应该接受三个 int 参数。我问他这个问题,他的回答是“必须在函数开始时使用提供的种子参数调用 srand() 函数。必须在调用 rand() 之前调用它。”我回答说我确实做到了(如您在上面看到的),我仍在等待他的回复。
  • 那我觉得你是金子。希望你能找到他的问题。
猜你喜欢
  • 2021-05-04
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 2021-03-11
相关资源
最近更新 更多