Reputation: 31
int main(){
unsigned int fstNumb = 0, sndNumb = 0;
cout << "Choose the first number: ";
cin >> fstNumb;
cout << "\nChoose the second number: ";
cin >> sndNumb;
cout << "\nNow click \'m\' to multiply, \'a\' to add or \'d\' to divide: ";
char option = '\0';
cin >> option; cout << "\n\n";
float result;
if (option == 'm'){
result = fstNumb * sndNumb;
cout << result;
}
else if (option == 'a'){
result = fstNumb + sndNumb;
cout << result;
}
else if (option == 'd') {
if (fstNumb || sndNumb == 0)
cout << "Cannot divide with 0 :/";
else {
cout << "You want the " << fstNumb << " or " << sndNumb << " to be divided?\n";
cout << "Press 1 for " << fstNumb << " or 2 for " << sndNumb;
char option2 = '\0';
cin >> option2;
if (option2 == 1){
cout << "\nYou chose " << fstNumb;
cout << "\nWanna divide it by how much?: ";
unsigned short division;
cin >> division;
if (division == 0){
cout << "\nCannot divide by 0!";
}
else{
result = fstNumb / division;
}
}
else if (option2 == 2){
cout << "\nYou chose " << sndNumb;
cout << "\nWanna divide it by how much?: ";
unsigned short division;
cin >> division;
result = sndNumb / division;
}
else
cout << "You must choose one of those 2 numbers!\n";
}
}
else
cout << "That's none of the letters I asked you.\n";
}
That if (fstNumb || sndNumb == 0)
always displays even when none of the integers are 0
, what's the problem?
Note that I'm not using boolean variables, but that shouldn't be a problem I guess.
Upvotes: 0
Views: 202
Reputation: 3399
if (fstNumb || sndNumb == 0)
is as same as
if (fstNumb != 0 || sndNumb == 0)
Change this part to (if you don't expect answer as 0),
if (fstNumb == 0 || sndNumb == 0)
But if there is no problem to get 0 as answer,
if ( sndNumb == 0)
Upvotes: 2
Reputation: 3800
Change condition if (fstNumb || sndNumb == 0)
to if (sndNumb == 0)
Because first number can be 0
.
Input : 0 12
Answer : 0
Upvotes: 0
Reputation: 44851
Short answer: Your logic is incorrect. if (fstNumb || sndNumb == 0)
is the same as if ( (fstNumb != 0) || (sndNumb == 0) )
, but you want if (fstNumb == 0 || sndNumb == 0)
. Change it to the latter and it will work as expected.
To explain why "Cannot divide with 0 :/"
displays even if neither fstNumb
nor sndNumb
is 0
:
If fstNumb
is nonzero, then it evaluates as true when treated as a boolean (zero is false; everything else is true). ||
has lower precedence than ==
, so the whole expression evaluates to fstNumb || (sndNumb == 0)
. When fstNumb != 0
, that expression is the same as true || (sndNumb == 0)
, which is always true.
Upvotes: 1
Reputation: 55448
if (fstNumb || sndNumb == 0)
is not the same thing as if (fstNumb == 0 || sndNumb == 0)
Upvotes: 5