So I have to write a simple calculator program that performs a chosen operation and keeps a running total using switch/case statements. For some reason my program ignores the first and third case statements. It will subtract and divide, but not add or multiply. When I swap the order in the code, whatever operations I place in the first and third slots won't be performed. What gives?
#include <iostream>
#include <string>
usingnamespace std;
//Adds, subtracts, multiplies and divides
//per the user's request and keeps a running total
int main()
{
double total, number;
char operand;
total = 0;
do
{
cout << "Current total is " << total << endl;
cout << "Enter an operation: + - * / (or enter X to exit):";
cin >> operand;
if ((operand == '+') || (operand == '-') || (operand == '*') || (operand == '/'))
{
cout << "Enter a number: ";
cin >> number;
switch (operand)
{
case'+':
total = total + number;
case'-':
total = total - number;
case'*':
total = number * total;
case'/':
if (number != 0)
{
total = total / number;
}
else
{
cout << "Can not divide by zero!" << endl;
}
};
}
} while (operand != 'X');
}
Oh, and is there a way to end the program when the user types X using switch/case and without using return()? My instructor gives these 'helpful' answers that are probably meant to make me think but really just make me want to hit my computer with a hammer. Help is appreciated.
Labeling the cases with numbers is a good idea, but it is forbidden by the instructor. Besides, the second and fourth case statements work; what is up with the first and third?
Thanks for trying, yoked. If anyone else wants to try, I added in a simple cout to make it output the operand if it executed the first case statement and it did so. So the first and third case statements are being executed, but for some reason in those two statements the total is not being updated. Either the arithmetic is not being done or I don't know what. Help, anyone?
Nevermind, I figured it out. I forgot the breaks in my case statements. How dumb of me. If you start with 0 (or any number) and then add 2, subtract 2, multiply by 2, and divide by 2, you get back to zero. If you just subtract 2, multiply by 2, and divide by 2, you never cancel the subtraction and get negative 2.
As tempted as I am to delete this to cover my stupid tracks, I'll leave it up for future Nittany Lions also afflicted by the stupid who take this course.