/*******************************************************/ //switch1.cpp //R.A. Hillayrd //Last Modified 09/24/2001 // //program to compute a simple arithmetic expression //using a switch statement /*******************************************************/ #include<iostream> using namespace std; int main() { int leftOperand; int rightOperand; char op; int result; //prompt user and extract desired operation cout << "Enter a simple expression " << "(number operator number) : "; cin >> leftOperand >> op >> rightOperand; switch(op) { case '+' : result = leftOperand + rightOperand; break; case '-' : result = leftOperand - rightOperand; break; case '*' : result = leftOperand * rightOperand; break; case '/' : if(rightOperand != 0) result = leftOperand / rightOperand; else { cout << leftOperand << "/" << rightOperand << " cannot be computed - denominator is 0\n"; return 1; } break; default : cout << op<< " is undefined\n"; return 1; }//end switch cout << leftOperand << op << rightOperand << " = " << result << endl; }//end main
/*************************************************************/
Enter a simple expression (number operator number) : 5+5 5+5 = 10 Enter a simple expression (number operator number) : 5*6 5*6 = 30 Enter a simple expression (number operator number) : 9/3 9/3 = 3 Enter a simple expression (number operator number) : 9/4 9/4 = 2 Enter a simple expression (number operator number) : 9/0 9/0 cannot be computed - denominator is 0 Enter a simple expression (number operator number) : 9%3 % is undefined