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";
}
即使(fstNumb || sndNumb == 0)
没有一个整数,如果0
始终显示,那么问题是什么?
请注意,我没有使用布尔变量,但我认为这不应该是一个问题。
答案 0 :(得分:5)
if (fstNumb || sndNumb == 0)
与if (fstNumb == 0 || sndNumb == 0)
答案 1 :(得分:2)
if (fstNumb || sndNumb == 0)
与
相同if (fstNumb != 0 || sndNumb == 0)
将此部分更改为(如果您不希望答案为0),
if (fstNumb == 0 || sndNumb == 0)
但如果得到0作为答案没有问题,
if ( sndNumb == 0)
答案 2 :(得分:1)
简答:您的逻辑错误。 if (fstNumb || sndNumb == 0)
与if ( (fstNumb != 0) || (sndNumb == 0) )
相同,但您需要if (fstNumb == 0 || sndNumb == 0)
。将其更改为后者,它将按预期工作。
解释为什么"Cannot divide with 0 :/"
显示,即使fstNumb
和sndNumb
都不是0
:
如果fstNumb
非零,那么当被视为布尔值时,它的计算结果为真(零为假;其他一切都为真)。 ||
的优先级低于==
,因此整个表达式的计算结果为fstNumb || (sndNumb == 0)
。当fstNumb != 0
时,该表达式与true || (sndNumb == 0)
相同,始终为真。
答案 3 :(得分:0)
将条件if (fstNumb || sndNumb == 0)
更改为if (sndNumb == 0)
因为第一个数字可以是0
。
Input : 0 12
Answer : 0