Simulates the work of a simple arithmetic device. Assuming that the calculator can only perform subtraction operations, the operands and results are integers, and the 4 operators have the same precedence, calculated in left-to-right order.
Input format:
The input gives a arithmetic calculation in a row, with no spaces and at least one operand. An equal sign "=" indicates the end of the input.
Output format:
Outputs the result of a calculation in a row, or if the division denominator is 0 or has an illegal operator, the error message "error" is output.
Input Sample:
1+2*10-10/2=
Sample output:
10
#include <iostream> #include <stdio.h> #include <math.h> #include <string>double compute (char c , double op1,double op2) {if (c== ' + ') return Op1+op2;else if (c== '-') return Op1-op2;else if (c== ' * ') return Op1*op2;else {RET Urn Op1/op2;} }//123+456/2=//with 123 as result,+ as Lastop, wait until the second operand temp=456,//and so on encountered/, will be 123+456 calculated, as result,/as lastop//detected =, The last result is calculated as int main () {double result; char c; Double Temp=0;char lastop= ' + '; while ((C=getchar ()) = ' = ') {if (c>= ' 0 ' &&c<= ' 9 ') {temp=10*temp+c-' 0 '; } else if (c== ' + ') {if (lastop== '/' &&temp==0) {printf ("ERROR"); return 0; } else {Result=compute (lastop,result,temp); } lastop= ' + '; Temp=0; } else if (c== '-') {if (lastop== '/' &&temp==0) {printf ("ERROR"); return 0; } else {Result=compute (lastop,result,temp); } lastop= '-'; Temp=0; } else if (c== ' * ') {if (lastop== '/' &&temp==0 ' {printf ("ERROR"); return 0; } else {Result=compute (lastop,result,temp); } lastop= ' * '; Temp=0; } else if (c== '/') {if (lastop== '/' &&temp==0) {printf ("ERROR"); return 0; } else {Result=compute (lastop,result,temp); } lastop= '/'; Temp=0; } else if (c== ') {}else{printf ("ERROR"); return 0; }} if (lastop== '/' &&temp==0) {printf ("ERROR"); return 0; } else{Result=compute (lastop,result,temp);} printf ("%d", (int) result); return 0;}
Cycle-17. Simple Calculators (20)