In C++, make a program to calculate simple math problems. First, ask the user fo
ID: 3787302 • Letter: I
Question
In C++, make a program to calculate simple math problems.
First, ask the user for the first number. Then the operation (-, +, *). Then the second number..
Next, display the result. Then, show a menu with three choices. The first choice will be to use the result in a new calculation. The second will be to make a new calulation. The third will be an exit option.
If the user chooses the first option, it should ask for opertaion (+, *, etc.) and second number. Next, display new result. Then it will show the menu from before.
Explanation / Answer
#include <iostream>
using namespace std;
int menu(){
int choice;
cout << "1. Use the result for for another calculation. ";
cout << "2. Make a new calculation. ";
cout << "3. Exit ";
cout << "Enter your choice: ";
cin >> choice;
return choice;
}
int calculate(int num1, char op, int num2){
int result;
switch(op){
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
}
return result;
}
int main(){
int firstNumber, secondNumber, result;
char op;
cout << "Enter the first number: ";
cin >> firstNumber;
cout << "Enter the operator(+, -, *): ";
cin >> op;
cout << "Enter the second number: ";
cin >> secondNumber;
result = calculate(firstNumber, op, secondNumber);
cout << firstNumber << " " << op << " " << secondNumber << " = " << result << " ";
while(true){
int more = menu();
switch(more){
case 1:
firstNumber = result;
cout << "Enter the operator(+, -, *): ";
cin >> op;
cout << "Enter the second number: ";
cin >> secondNumber;
break;
case 2:
cout << "Enter the first number: ";
cin >> firstNumber;
cout << "Enter the operator(+, -, *): ";
cin >> op;
cout << "Enter the second number: ";
cin >> secondNumber;
break;
case 3:
return 0;
}
result = calculate(firstNumber, op, secondNumber);
cout << firstNumber << " " << op << " " << secondNumber << " = " << result << " ";
}
}