在具有相同种子的同一程序中对srand()的第二次调用不会为连续的rand()生成相同的值



我正在为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
}

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

祝你好运。

最新更新