-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA12mathquizforK-8students.cpp
78 lines (60 loc) · 2.03 KB
/
A12mathquizforK-8students.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Math Quiz for K-8 students
// With Random Number Simulation
// By Emily Dayanghirang
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
const int UPPER_LIMIT = 12;
const int LOWER_LIMIT = 1;
const int RANGE = UPPER_LIMIT - LOWER_LIMIT + 1;
int firstOperand, secondOperand,
userAnswer, correctAnswer;
// Seed the random number generator
srand(time(0));
cout << "\nEnter -1 to exit the program\n";
do
{
// Assign a random number for the operands
firstOperand = rand() % RANGE + LOWER_LIMIT;
secondOperand = rand() % RANGE + LOWER_LIMIT;
// Prompt user
cout << "\nHow much is " << firstOperand
<< " times " << secondOperand << "? ";
cin >> userAnswer;
// Multiplication computation
correctAnswer = firstOperand * secondOperand;
// User enters the correct answer
if(userAnswer == correctAnswer)
cout << "\nVery good!\n";
while(userAnswer != correctAnswer && userAnswer != -1)
{
// Input validation for int
if (cin.fail())
{
cout << "\nERROR: Please input an integer.\n";
cin.clear();
cin.ignore(1000,'\n');
// Re-prompt
cout << "\nHow much is " << firstOperand
<< " times " << secondOperand << "? ";
cin >> userAnswer;
}
else
{
cout << "\nIncorrect Answer. Please try again.\n";
// Re-prompt user for the same question
cout << "\nHow much is " << firstOperand
<< " times " << secondOperand << "? ";
cin >> userAnswer;
}
if(userAnswer == correctAnswer)
cout << "\nVery good!\n";
}
// Loop back to ask a new mathematical question
}while( userAnswer == correctAnswer && userAnswer != -1);
cout << "\nGoodbye!\n";
return 0;
}