I'm working on a simple "addition questions" program for my intro to C++ class. My instructor uses a test driver to grade our code. The test driver first runs the program using his code, and then runs my function and compares the two.
In this code, we're supposed to generate random numbers to give the user simple addition problems. They enter the answer and the program keeps track of how many they got correct, and returns the number of correct answers to the main function.
As I understand it, srand() will generate the same list of numbers if the seed is the same. The problem I'm having is even though I put srand(seed) at the top of my function, the successive numbers generated by each rand() call are still different. As I understood it, if you recall srand with the same seed, it will reset the number generator and give you the same chain of numbers from rand().
Because he uses a test driver to grade, the driver is telling me almost all of my results are wrong, but it's because the driver does not actually calculate my random generated numbers, it just looks for the same answers as what he got in his version of the program. So the problem is for some reason calling srand(seed) is not using the same numbers.
This could be a problem with his driver, if it is sending a different number to my function for seed than he used, but it could also be that I put srand() in the wrong place, or I'm not using it correctly.
Can anyone confirm if the use of srand(seed) in my code would reset and use the same numbers given that seed value is the same?
Here's my function:
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
}