通常如何读取程序中的逻辑表达式?例如:
(1 == x) && ( 2 > x++)? (x=1)
?的目的是什么,为表达式生成正确答案的思维方式是什么?
发布于 2019-02-05 09:27:49
声明如下:
var value = (boolean expression) ? some value if `true` : some value if `false`是一种特殊的条件语句,它使用三元算子 (?:)根据布尔表达式将值赋值给变量。
这是一种更简洁的表达条件语句的方式:
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发布于 2019-02-05 09:31:46
此语句甚至不编译,?与:一起用作三元操作符。
在(x=1)之后,您应该拥有其他分支,仅举一个例子:
(1 == x) && ( 2 > x++) ? (x=1) : (x = 2)
这个布尔表达式的计算方法如下,假设x为1:
(1 == x) =真(2 > x++) = falsetrue && false = false无论x的值如何,表达式都将始终为false。
发布于 2019-02-05 09:33:21
(1 == x) && ( 2 > x++)? (x=1);?代表三元运算。,如果?的左侧为真,则它紧跟右侧。
在您的示例中,如果( 2 > x++)为true,则x的值为1。但是要向( 2 > x++)移动,左表达式必须为true,这意味着x==1,因此如果(1 == x)为true,那么( 2 > x++)为true,则总体条件为true。
https://stackoverflow.com/questions/54531092
复制相似问题