首页 文章

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

提问于
浏览
0

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

在这段代码中,我们应该生成随机数,以便为用户提供简单的添加问题 . 他们输入答案,程序会跟踪他们纠正的数量,并返回主函数的正确答案数 .

据我了解,如果种子相同,srand()将生成相同的数字列表 . 我遇到的问题是即使我把srand(种子)放在我的函数的顶部,每个rand()调用生成的连续数字仍然不同 . 据我所知,如果你用相同的种子回忆srand,它将重置数字生成器并从rand()给你相同的数字链 .

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

这可能是他的驱动程序的一个问题,如果它向我的函数发送一个与他使用的不同的数字,但也可能是我把srand()放在错误的地方,或者我没有正确使用它 .

任何人都可以确认我的代码中srand(种子)的使用是否会重置并使用相同的数字,因为种子值是相同的?

这是我的功能:

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
}

1 回答

  • 0

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

    祝好运 .

相关问题