为什么if语句无效
Why is if statement not working
我是编程新手,无法解决这个问题,我已经到处寻找答案。当从function2
传递cin >> 1
时,似乎不会读取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);
}
尽管user154248的答案(至少部分)是正确的,但您可能会感兴趣的是为什么。。。
原因是operator!=
具有较高的优先级(即在operator||
之前进行评估)。所以你的if子句等价于if((i != 0) || 1)
。
此外,如果在期望布尔参数的表达式中使用任何不等于0(null/zero)的值,则会将其计算为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
。
尝试更改此项:
if (i != 0 || 1 )
对此:
if (i != 0 || i != 1 )
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- c++:if 语句无法正常运行,并继续执行无效输出
- 如何使用libpq库和C 绑定无效的语句
- 获取控制权到达非无效函数警告的末尾,尽管我在 th 函数中有返回语句
- 如何引用无效的输入,然后重新输入和如果其他语句
- 提示再次运行程序:修复他们是否输入了无效语句
- switch 语句中从 'const char*' 到 'char' 的转换无效
- C++将向量传递给重载类——有些调用语句有效,有些则无效
- 在 && 语句的后半部分进行无效操作是否安全?
- 以下C++模板程序中的无效语句是什么
- 警告:语句无效 (C++)
- 如何在开关语句中更改指针。错误:从'const char*'到'char'的转换无效
- Qt-Sql INSERT语句无效
- 为什么if语句无效