读取和解释程序中的逻辑表达式

Reading and interpreting a logical expression in a program

你平时是怎么读懂程序中的逻辑表达式的?例如:

(1 == x) && ( 2 > x++)? (x=1)

?的目的是什么,表达式正确答案的生成思路是什么?

以下语句:

var value = (boolean expression) ? some value if `true` : some value if `false`

是一个特殊的条件语句,它使用Ternary Operator?:)根据布尔表达式为变量赋值。

这是表达此条件语句的更简洁的方式:

var value;

//this is the boolean expression you evaluate before the question mark
if (boolean expression is true) {
    //this is what you assign after the question mark
    value = some value if true;
}
else {
    //this is what you assign after the colon
    value = some other value if false;
}

因此,根据您的示例(顺便说一句,语法错误),应该是这样的:

if ((1 == x) && (2 > x++)){
    x = 1;
}
else {
    /*This is the value that would be put after the colon
     *(which is missing in your example, and would cause a compiler error)
     */
    x = some other value; 
}

这将转化为:

x = (1 == x) && (2 > x++) ? 1 : some other value

此语句甚至无法编译,?: 一起用作三元运算符。

(x=1) 之后你应该有 else 分支,举个例子:

(1 == x) && ( 2 > x++) ? (x=1) : (x = 2)

这个布尔表达式的计算方式如下,假设 x 是 1 :

  1. (1 == x) = 真
  2. (2 > x++) = 假
  3. true && false = 假

无论你的 x 值如何,你的表达式总是假的

 (1 == x) && ( 2 > x++)? (x=1);

?代表三元运算。 ,如果 ? 的左侧为真,则它紧跟右侧。

在您的情况下,如果 ( 2 > x++) 为真,则 x 的值将为 1。但是要向 ( 2 > x++) 移动,您的左侧表达式必须为真,这意味着 x==1, 因此,如果 (1 == x) 为真,因此 ( 2 > x++) 为真,则您的总体条件为真。

除了关于?:的相关注释需要,还需要下面的"understand" 例子中代码的运行:

&& 的计算顺序意味着 ´ ( 2 > x++) ´ 将 不会 全部被计算,除非 ´(1 == x)´ 为真。特别意味着不会发生 x++ 的副作用。

´x=1´ 是一个 assignment 所以乍一看它不像一个计算值的表达式,但在 java 中,赋值本身就是接受赋值的表达式。