为什么逻辑和顺序改变会给出不同的输出?
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;
}
我完全理解第二个输出但无法理解第二个输出中的第一个 output.As 并且第一个操作数为 0 然后它不评估第二个运算符并给出 0 但首先它评估-1(这是真的非零)然后它必须评估 0 并给出 0 作为结果而不是 -1.
你是误解的受害者operator precedence。运算符 <<
的优先级高于 &&
,因此它将在 &&
之前被完全计算。
您的陈述等同于:
(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 从第二行打印。
#include<iostream>
using namespace std;
int main(){
cout<<-1&&0; //output is -1
cout<<0&&-1; //output is 0
return 10;
}
我完全理解第二个输出但无法理解第二个输出中的第一个 output.As 并且第一个操作数为 0 然后它不评估第二个运算符并给出 0 但首先它评估-1(这是真的非零)然后它必须评估 0 并给出 0 作为结果而不是 -1.
你是误解的受害者operator precedence。运算符 <<
的优先级高于 &&
,因此它将在 &&
之前被完全计算。
您的陈述等同于:
(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 从第二行打印。