// This program evaluates simple expressions // number1 operator1 number2 operator2 number3 // e.g., 3 + 4 * 5 // the program computes the answer using C++ // precedence, i.e., * comes before +. // For this simple example, we will just use // the operators *, +, /, -. // // double evaluate(double, char, double ); int priority(char); #include #include int main() { double n1, n2, n3; double result; char op1, op2; int op1_priority, op2_priority; cout << "Enter an expression: "; cin >> n1 >> op1 >> n2 >> op2 >> n3; // decide whether op1 has higher precedence than op2 op1_priority = priority(op1); op2_priority = priority(op2); // if op2 has higher priority than op1 if (op2_priority < op1_priority) { result = evaluate(n2, op2, n3); result = evaluate(n1, op1, result); } else { // first evaluate op1, then evaluate op2 result = evaluate(n1, op1, n2); result = evaluate(result, op2, n3); } cout << "The answer is " << result << endl; } double evaluate(double operand1, char op, double operand2) { double value = 0; if (op == '+') value = operand1 + operand2; else if (op == '-') value = operand1 - operand2; else if (op == '*') value = operand1 * operand2; else if (op == '/') value = operand1 / operand2; else if (op == '%') value = int(operand1) % int(operand2); else if (op == '^') value = pow(operand1, operand2); else cout << "invalid operator " << op << endl; return value; } int priority(char op) { int op_priority; op_priority = 1; if (op == '/' || op == '*' || op == '%') op_priority = 2; if (op == '+' || op == '-') op_priority = 3; return op_priority; }