Your random values are initialised just once, since they're global variables.
Your first code was better, in the sense that it had a function.
Don't try to write everything at once. You can add useful bits of functionality 5 lines at a time.
For example, you might start with this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void quizMultiply( int x, int y ) {
int correct = x * y;
int response;
cout << "What is " << x << " times " << y << "?" << endl;
cin >> response;
if ( response != correct )
cout << "Wrong" << endl;
else
cout << "Correct" << endl;
}
int main ( ) {
quizMultiply(rand()%10,rand()%10);
}
|
In two further iterations, you put a while loop in main (to run more quizzes), and you put a while loop in the function (to allow more guesses at a given question).
So you might end up with something like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
void quizMultiply( int x, int y ) {
int correct = x * y;
int response;
do {
cout << "What is " << x << " times " << y << "?" << endl;
cin >> response;
if ( response != correct )
cout << "Wrong" << endl;
else
cout << "Correct" << endl;
} while ( response != correct );
}
int main ( ) {
char yorn;
do {
quizMultiply(rand()%10,rand()%10);
cout << "Do you want another go(Y/N)?" << endl;
cin >> yorn;
} while ( yorn == 'Y' || yorn == 'y' );
}
|
Say you then wanted to add a limit to how many times they could guess.
You figure that changing quizMultiply is the thing to do, but that might make the function messy.
So first extract the actual Q/A from the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
bool multTest(int x, int y) {
int correct = x * y;
cout << "What is " << x << " times " << y << "?" << endl;
int response;
cin >> response;
if ( response != correct )
cout << "Wrong" << endl;
else
cout << "Correct" << endl;
return response == correct;
}
void quizMultiply( int x, int y ) {
bool correct;
do {
correct = multTest(x,y);
} while ( !correct );
}
|
Notice that there was no actual change to what the code does at this stage.
A lot of coding is just cleaning things up to make your life easier in the long run. Sure you could pile everything into main, but it would be nested 6 levels deep, 100's of lines long and a complete PITA to change.
Then it's easy to add in a counter to the now much simplified quizMultiply function.
1 2 3 4 5 6 7 8 9 10 11
|
void quizMultiply( int x, int y ) {
int guesses = 0;
bool correct;
do {
correct = multTest(x,y);
if ( !correct )
guesses++;
} while ( guesses < 3 && !correct );
if ( !correct )
cout << "Better luck next time" << endl;
}
|