我是编程新手,不能解决这个问题,我已经找遍了所有我能想到的答案。当cin >> 1
从function2
传递时,function1
if (m != 0 || 1)
中的if语句似乎未被读取。这是我的代码,任何帮助都将不胜感激。
#include <iostream>
void function1(int i);
int main() {
using namespace std;
int i;
function1(i);
return 0;
}
----------------------------------------------------------------------------
#include <iostream>
void function2();
void function1(int i) {
using namespace std;
if (i != 0 || 1 ) /* not working when the variable 'i' is passed from function2 */ {
cout << endl << "i != 0 || 1" << endl;
function2();
}
else if (i == 0 || 1) {
if (i == 0) {
cout << endl << "m == 0" << endl;
}
else if (i == 1) {
cout << endl << "m == 1" << endl;
}
}
}
----------------------------------------------------------------------------
#include <iostream>
void function1(int i);
void function2() {
using namespace std;
int i;
cout << endl << "type 0 or 1" << endl;
cin >> i; /* type 1 or 0 in here */
function1(i);
}
发布于 2016-07-24 17:30:44
尽管user154248的答案是正确的(至少部分正确),但您可能会对原因感兴趣……
原因是operator!=
具有更高的优先级(即在operator||
之前评估)。所以if子句等同于if((i != 0) || 1)
。
此外,如果在需要布尔参数的表达式中使用,则任何不等于0(null/零)的值都将被计算为true
,因此您将获得if((i != 0) || true)
。现在,无论i != 0
的计算结果是什么,整个表达式x || true
都将得到true
。
最后-我们回到用户154248的答案...
但是,还有一个问题:i != 0 || i != 1
也将始终计算为true:如果i等于0,i != 1
将计算为true,如果I等于1,则i != 0
将计算为true...
您真正需要的是i != 0 && i != 1
。
发布于 2016-07-24 17:15:52
尝试更改此设置:
if (i != 0 || 1 )
要这样做:
if (i != 0 || i != 1 )
https://stackoverflow.com/questions/38554633
复制