I'm trying to do a calculator, I have done the functions for the operators(+ , - , / , *) ..
My question lies in my main() function in the while loop.
AT the end if I enter a wrong option, for example '6', then it asks me to eneter again but if I enter a wrong option again, it just exits the loop.
|| means "OR", so you're asking if option is bigger/equal to 1 OR lesser/equal to 4. 6 is bigger or equal than 1, so it calls the break. note that every single number in the universe is included in this statement (anything bigger than 1 and lower than 4)
i think you wanted if (option >= 1 && option <= 4)
which means "if number is bigger/equal to 1 AND lesser/equal to 4".
#include <iostream>
usingnamespace std;
int main(){
//cout << "Hello World";
//cin.get();
int a, b, option;
cout << "Please enter two number: ";
cin >> a;
cin >> b;
cout << "To add press 1 \nTo subtract press 2\nTo divide press 3\nTo multiply press 4: \n";
//cin >> option;
//cout << endl << endl;
while (option != 1 || option != 2 || option != 3 || option != 4){
cin >> option;
switch (option){
case 1:
cout << "The answer is: " << a+b << endl;
break;
case 2:
cout << "The answer is: " << a-b << endl;
break;
case 3:
cout << "The answer is: " << a/b << endl;
break;
case 4:
cout << "The answer is: " << a*b << endl;
break;
default:
cout << "Incorrect Value, Please try again: ";
//cin >> option;
break;
}
if (option >= 1 && option <= 4){
break;
}
}
}
so every time the loop runs, it asks for the input.
hint: use floats instead of ints, or you will not get correct results when dividing numbers.
hint2: do not use system("pause"). i know that you probably just wanted to test and study and stuff, but it's a bad habit. search around for alternatives.