// 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 *, +, /, -. // // #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 = 1; if (op1 == '+' || op1 == '-') op1_priority = 2; op2_priority = 1; if (op2 == '+' || op2 == '-') op2_priority = 2; // if op2 has higher priority than op1 if (op2_priority < op1_priority) { // first evaluate op2, then evaluate op1 if (op2 == '+') result = n2 + n3; else if (op2 == '*') result = n2 * n3; else if (op2 == '-') result = n2 - n3; else if (op2 == '/') result = n2 / n3; if (op1 == '+') result = n1 + result; else if (op1 == '*') result = n1 * result; else if (op1 == '-') result = n1 - result; else if (op1 == '/') result = n1 / result; } else { // first evaluate op1, then evaluate op2 // here is a way to do this first step for op1 // using if / else if / else construct // //if (op1 == '+') // result = n1 + n2; //else if (op1 == '*') // result = n1 * n2; //else if (op1 == '-') // result = n1 - n2; //else if (op1 == '/') // result = n1 / n2; //else // cout << "ERROR: op1 is invalid\n"; // here is a way to do the same thing using a switch statement switch (op1) { case '+': result = n1 + n2; break; case '*': result = n1 * n2; break; case '-': result = n1 - n2; break; case '/': result = n1 / n2; break; default: cout << "ERROR: op1 is invalid\n"; } if (op2 == '+') result = result + n3; if (op2 == '*') result = result * n3; if (op2 == '-') result = result - n3; if (op2 == '/') result = result / n3; } cout << "The answer is " << result << endl; }