This is an addition quiz that I have been working on which basically asks you questions then tells you if you were right or wrong and keeps track of your score. It asks you to continue or quit at the end of every question. My question is, in my current setup, the random numbers i get are always the same (though different each time i start the program). I want to know how i can make them different for every question but still have A+B = C so that i can determine if the answer is correct or incorrect. Any help is appreciated.
I know it looks complicated but this is probably due to my inexperience and inability to condense it.
int result;
int solution;
int score;
int play;
int question;
int end_game;
int a,b,c;
time_t seconds;
time(&seconds);
srand ((unsigned int) seconds);
a = rand() % 100 + 1;
time(&seconds);
srand ((unsigned int) seconds);
b = rand() % 100 + 1;
c = (a+b);
score = 0;
question = 1;
end_game = 0;
cout<< "This is an addition game\n";
cout<< "Type in the answer then press enter\n";
cout<< "Press 1 now to play or press 0 to quit:";
srand(time(NULL));
cin>> play;
cin.ignore();
if ( play > 0 ) { cout<< "\nGood Luck!\n" ;}
do{
do{
cout<< "\nQuestion " << question << "\n";
cout<< a << "+" << b << "=__\n";
cin>> result;
cin.ignore();
if (result == c) {cout<< "\nCorrect";
score = score + 1 ;
cout<< "\nYour current score is " << score << "\n";}
else { cout<< "\nIncorrect\n";
cout<< "The correct answer was " << c << "\n";
cout<< "Your current score is still " << score << "\n";
}
cout<< "Press 1 to continue or 0 to quit \n";
cin>> play;
cin.ignore();
if (play > 0) { question = question + 1;
cout << "\n";}
} while (play > 0);
cout<< "\n \nYour Final Score was " << score << "\n";
cout<< "Press 0 to quit or 1 to restart \n";
cin>> end_game;
cin.ignore();
If you seed the RNG with the same value every time, you will get the same number every time. An RNG typically should only be seeded once at program startup.
Basically...
Call srand() exactly once when the program starts. Do not call it every time you call rand().
Your srand is in a loop, and is therefore being called multiple times.
Take it out of the loop. Very simply... do it as the very first thing in main, and then never do it again:
1 2 3 4 5
int main()
{
srand( (unsigned)time(0) );
// ...the rest of your program
Also, it's possible that you are not calling rand() when you want to produce new numbers. You have a lot of loops, no comments, and inconsistent indentation, so it's difficult for me to really follow exactly what it is you're trying to do... but I suspect that you're doing something like this:
1 2 3 4 5 6
a = rand();
while( user_wants_to_keep_playing )
{
// check 'a' here
}
The problem with this is that if the user wants to play again, 'a' will remember its old value. If you want to pick new values for 'a', you must call rand() again to select a new number.