In: Computer Science
die's job is to output an error message alarmingly and terminate the program. You may copy my
function definition, or use your own:
// The following 4 lines should be present if we have a die function:
#include <iostream> // cout, endl
#include <string> // string
#include <cstdlib> // exit, EXIT_FAILURE
using namespace std;
bool die(const string & msg){
cout <<"Fatal error: " <<msg <<endl;
exit(EXIT_FAILURE);
}
4. Use rand to randomly choose one of the five operators * / % + - .
Use rand again to choose a random int in the range [1, 20].
Use rand again to choose a second random int in the range [1, 20].
Ask the user what the answer to the corresponding equation is.
C&d on input failure
Tell the user whether he's correct.
An example run of your program might go as
What's the answer to 14 * 3 ?
42
Yes, that's the right answer!
4>
C++ Code:
Output Snapshot:
Text Code:
#include <iostream>
using namespace std;
int main()
{
// Character Variable to store operatorSymbol
char operatorSymbol[6] = {'*','/','%','+','-'};
// Generating random number between 0 to 4 and storing it in
operatorRandomNum
int operatorRandomNum = rand() % 5;
// Generating random number between 1 to 20 and storing it in
firstRandomNum
int firstRandomNum = rand() % 20 + 1;
// Generating random number between 1 to 20 and storing it in
secondRandomNum
int secondRandomNum = rand() % 20 + 1;
// Variable to store user input answer
int userInputResult;
// Prompting user to provide answer
cout << "What's the answer to " << firstRandomNum
<< " " << operatorSymbol[operatorRandomNum] << "
" << secondRandomNum << "?" << endl;
// Storing user input in userInputResult variable
cin >> userInputResult;
// Variable to store actual calculated correct answer
int actualResult;
switch(operatorRandomNum){
case 0: // * Multiplication Operation
actualResult = firstRandomNum*secondRandomNum;
break;
case 1: // / Division Operation
actualResult = firstRandomNum/secondRandomNum;
break;
case 2: // % Modulo Operation
actualResult = firstRandomNum%secondRandomNum;
break;
case 3: // + Addition Operation
actualResult = firstRandomNum+secondRandomNum;
break;
case 4: // * Subtraction Operation
actualResult = firstRandomNum-secondRandomNum;
break;
}
// Displaying if user provided answer is correct or not
if(userInputResult == actualResult){
cout << "Yes, that's the right answer!";
} else {
cout << "No, that's the wrong answer!";
}
return 0;
}
Explanation: