[英]Conditional operators error
I'm having trouble understanding why the following section of code is returning x and not b. 我很难理解为什么以下代码部分返回x而不是b。
#include <iostream>
using namespace std;
int main()
{
int x = 12;
int a = 1;
int b = 0;
cout << "answer: " << (x < a && 1 ? a : (x > b && 0 ? b : x)) << endl;
return 0;
}
My working is: 我的工作是:
x is NOT lower than a [logical and) 1, move to second set of brackets. x不低于[逻辑和] 1,移至第二组括号。
x IS larger than both 0 [logival and] 0 there fore the result should be 'b'. x IS大于0 [对数和] 0,因此结果应为'b'。
(as both statement equate to true, shouldn't the Result_if_true statement be the output?) (由于两个语句都等于true,因此Result_if_true语句不应该作为输出吗?)
x > b && 0
does not mean "x is larger than both b and 0". x > b && 0
并不意味着“x大于b和0大”。
Instead, it means: "x is larger than b, and 0 is a true statement". 相反,它的意思是:“ x大于b,0是真实的语句”。 The
&&
operator is a logical AND that connects two statements. &&
运算符是连接两个语句的逻辑AND。 You cannot use it in the loose way in which the word "and" is used in natural language. 您不能以自然语言使用“和”一词的宽松方式来使用它。
(x < a && 1 ? a : (x > b && 0 ? b : x))
is parsed as 被解析为
((x < a) && 1) ? a : (((x > b) && 0) ? b : x)
which is the same as 这与
(false && true) ? a : ((true && false) ? b : x)
ie 即
false ? a : (false ? b : x)
ie 即
x
In this expression 在这个表达中
(x < a && 1 ? a : (x > b && 0 ? b : x))
there is at first evaluated condition 首先有评估条件
x < a && 1
It is equal to false
because x is not less than a. 因为x不小于a,所以它等于
false
。
So the next expression that will be evaluated is 因此,将要计算的下一个表达式是
(x > b && 0 ? b : x)
In this expression condition 在这种表达条件下
x > b && 0
is obviously equal to false
显然等于
false
So the value of the whole expression will be the value of subexpression 所以整个表达式的值就是子表达式的值
x
and there will be outputed 并会输出
answer: 12
Your logical mistake is that expression 您的逻辑错误是该表达
x > b && 0
is not equivalent to 不等于
( x > b ) && ( x > 0 )
it is equivalent to 它等效于
( x > b ) && ( 0 )
As expression 作为表达
( 0 )
is equal to false
then and 等于
false
然后
( x > b ) && ( 0 )
is equal to false
等于
false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.