[英]Why do these programs performing the same calculation in a different order give me different output?
[英]why logical and with change of order give different output?
#include<iostream>
using namespace std;
int main(){
cout<<-1&&0; //output is -1
cout<<0&&-1; //output is 0
return 10;
}
我完全理解第二个输出,但无法理解第一个输出。在第二个输出和第一个操作数是0然后它不评估第二个运算符并给出0,但首先它评估-1(这是真的,因为它是非零)然后它有评估0并给出0作为结果而不是-1。
您是误解运算符优先级的受害者。 运算符<<
的优先级高于&&
,因此它将在&&
之前完全求值。
您的陈述相当于:
(cout << -1) && 0;
(cout << 0) && -1;
如果您希望首先评估&&
,则需要执行以下操作:
cout << (-1 && 0);
cout << (0 && -1);
这是一个操作顺序问题。 如果在逻辑运算周围添加括号,那么代码是有意义的:
#include<iostream>
using namespace std;
int main()
{
cout << (-1 && 0) << endl; //output is -1
cout << (0 && -1) << endl; //output is 0
return 10;
}
输出:
0
0
在原始代码中,<<和-1在-1 && 0之前被评估。
因此,从第一行打印-1,从第二行打印0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.