[英]C Program output confusion
Can someone explain why the output of this program is false?? 有人可以解释为什么这个程序的输出是假的?
x && y gives 1. Still the output is false. x && y给出1.仍然输出为false。
#include <stdio.h>
int main()
{
int x = 1, y = 2;
if(x && y == 1)
{
printf("true.");
}
else
{
printf("false.");
}
return 0;
}
Because ==
has a higher precedence than &&
So first this get's evaluated: 因为==
的优先级高于&&
所以首先评估这个优先级:
x && (y == 1)
y == 1 // 2 == 1
//Result: false
Which is false and then second: 哪个是假的,然后是第二个:
x && false //1 && false
//Result: false
So the if statement will be false 所以if语句将是false
For more information about operator precedence see here: http://en.cppreference.com/w/cpp/language/operator_precedence 有关运算符优先级的更多信息,请参见此处: http : //en.cppreference.com/w/cpp/language/operator_precedence
if(x && y == 1)
Is the same as 是相同的
if( ( x != 0 ) && ( y == 1 ) )
Here, x != 0
is true, but y == 1
is false. 这里, x != 0
为真,但y == 1
为假。 And since at least one of the operands of &&
is false, the condition evaluates to false and the else
part executes. 并且由于&&
至少一个操作数是假的,因此条件计算为false并且else
部分执行。
It clearly stated X = 1 & Y = 2; 它清楚地表明X = 1和Y = 2; Now with your expression 现在用你的表达
X && Y == 1
The expression is evaluated as Y == 1 (Precedence Rule, Also output is False) 表达式计算为Y == 1(优先规则,输出也为假)
X != 0 (Its True) X!= 0(正确)
Now && is Logical And Operator, so it evaluates to True only if both the parts in expression evaluates to True!!! 现在&&是逻辑和运算符,所以只有当表达式中的两个部分都计算为True时,它才会计算为True!
It's okay to false, then 2 and 2 and it is different from one. 这是假的,然后是2和2,它与一个不同。 What you're asking is whether both x and y both are worth 1. If this happens say true but false 你问的是x和y都是否值得1.如果发生这种情况则说真实但是错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.