【发布时间】: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 指出的那样,我想问题一定出在测试驱动程序中。是时候给我的导师发电子邮件了。谢谢大家。