I'm writing a pretty simple program for my first-year C++ class, where I utilize switch
statements to get a correct output depending on what two numbers and what special character is used between them (adding, subtracting, multiplying, dividing). The program uses a nested if
statement in the division case to check if the second number entered is zero, and a default
statement if none of the correct special characters are used.
The problem lies in the fact that if the user divides by zero, or uses an incorrect symbol, the console will display the intended error, but also the result, when it's only supposed to show the message.
I understand why it's displaying both lines, but I don't know of any way to fix it. I'm not allowed to change the switch
statement to an if
statement, and I'm not allowed to use additional functions or arrays.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
char operatr;
double operand1 = 0,
operand2 = 0,
result = 0;
cout << "Enter a binary expression of the form: operand operator operand ";
cin >> operand1 >> operatr >> operand2;
cout << endl << endl
<< "C.S.1428.002" << endl
<< "Lab Section: L17" << endl
<< "10/14/20" << endl << endl;
cout << fixed << setprecision(1);
switch ( operatr )
{
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if ( operand2 == 0)
{
cout << operand1 << " " << operatr << " " << operand2 << " " << "Division by zero produces an undefined result" << endl;
break;
}
else
{
result = operand1 / operand2;
break;
}
default:
cout << operand1 << " " << operatr << " " << operand2 << " Encountered unknown operator." << endl;
break;
}
cout << operand1 << " " << operatr << " " << operand2 << " = " << result << endl;
system("PAUSE>NUL");
return 0;
}