a C++ program that mimics a calculator. The program should take as input two int
ID: 3855755 • Letter: A
Question
a C++ program that mimics a calculator.
The program should take as input two integers and the operation to be performed.
Sample user inputs:
3 + 4
10 - 5
2 * 4
4 / 2
It should then output the numbers, the operator, and the result. (For division, if the denominator is zero, output an appropriate message: "Cannot divide by zero")
Sample outputs:
3 + 4 = 7
10 - 5 = 5
2 * 4 = 8
4 / 2 = 2
***Use switch statement for operators (+, -, *, /). If the user types a different operator, prompt the user: "Illegal Operation", and terminate the program.)
OUTPUT:
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
3 + 4
3 + 4 = 7
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
10 - 5
10 - 5 = 5
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
2 * 4
2 * 4 = 8
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
4 / 2
4 / 2 = 2
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
3 % 2
Illegal Operation.
**********************************************************************
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
3 / 0
Can't divide by 0.
*********************************************************************
Explanation / Answer
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,result;
char op;
cout<<" Enter two integer numbers with an arithmetic operator (ex. 3 + 4): "<<endl;
cin >>x>>op>>y;
//cout<<"x = "<<x<<" op = "<<op<<" y = "<<y;
switch(op)
{
case '+': result = x+y;
break;
case '-': result = x-y;
break;
case '*': result = x*y;
break;
case '/': if(y == 0)
{
cout<<" Cannot divide by zero";
exit(0); //if denominator is 0 raise error and exit
}
else
result = x/y;
break;
default : cout<<" Illegal Operation";
exit(0);
}
cout<<" "<<x<<" "<<op<<" "<<y<<" = "<<result;
return 0;
}
Output:
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
4/0
Cannot divide by zero
Enter two integer numbers with an arithmetic operator (ex. 3 + 4):
3 + 4
3 + 4 = 7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.