#include <iostream>
bool check_number(unsigned short int a, unsigned short int b) {
if ((a || b == 30) || a + b == 30) {
return true;
}
return false;
}
int main() {
std::cout << check_number(15, 16) << std::endl;
std::cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我得到“真实”结果?为什么不假呢,我们知道15+16就是31
if ((a || b == 30)不是“a 或 b 等于 30”,而是“(a) 或 (b 等于 30)”。As转换a为非零。truebool
所以你有了
if ((true || other condition) || just_another_condition)
Run Code Online (Sandbox Code Playgroud)
因为||是短路,所以整体条件是true。
如果您实际上想要“a 等于 30 或 b 等于 30”,那就是(a == 30) || (b == 30)。
最后但并非最不重要的一点是,如果您有这样的代码:
if (condition) {
return true;
} else {
return false;
}
Run Code Online (Sandbox Code Playgroud)
那么这只是return condition;