为什么三元表达式在 if 语句工作正常时不更新值?
Why ternary expression is not updating the value while if statement is working fine?
我也试过改变三元表达式来产生等效的结果:
is_balanced = (Math.abs(lh-rh)<=1) ? true:false;
static boolean is_balanced=true;
public static int balHeight(Node node) {
if(node==null) return 0;
int lh = balHeight(node.left);
int rh = balHeight(node.right);
if(Math.abs(lh-rh)>1) is_balanced = false;
**// ternary not working here
// is_balanced = Math.abs(lh-rh) > 1 ? false:true;**
return Math.max(lh,rh)+1;
}
等效代码为 is_balanced = Math.abs(lh - rh) > 1 ? false : is_balanced
。
(或者,没有三元:is_balanced = is_balanced && Math.abs(lh - rh) <= 1
。)
这是使用三元和不使用三元的示例代码,两者产生相同的结果。这意味着三元工作符合预期。
public class Test {
public static void main(String[] args) {
int lh = 5;
int rh = 10;
boolean balanced;
balanced = Math.abs(lh - rh) > 1;
System.out.println("General Assignment - " + balanced);
balanced = Math.abs(lh - rh) > 1 ? true : false;
System.out.println("Ternary Assignment - " + balanced);
}
}
输出-
General Assignment - true
Ternary Assignment - true
我也试过改变三元表达式来产生等效的结果:
is_balanced = (Math.abs(lh-rh)<=1) ? true:false;
static boolean is_balanced=true;
public static int balHeight(Node node) {
if(node==null) return 0;
int lh = balHeight(node.left);
int rh = balHeight(node.right);
if(Math.abs(lh-rh)>1) is_balanced = false;
**// ternary not working here
// is_balanced = Math.abs(lh-rh) > 1 ? false:true;**
return Math.max(lh,rh)+1;
}
等效代码为 is_balanced = Math.abs(lh - rh) > 1 ? false : is_balanced
。
(或者,没有三元:is_balanced = is_balanced && Math.abs(lh - rh) <= 1
。)
这是使用三元和不使用三元的示例代码,两者产生相同的结果。这意味着三元工作符合预期。
public class Test {
public static void main(String[] args) {
int lh = 5;
int rh = 10;
boolean balanced;
balanced = Math.abs(lh - rh) > 1;
System.out.println("General Assignment - " + balanced);
balanced = Math.abs(lh - rh) > 1 ? true : false;
System.out.println("Ternary Assignment - " + balanced);
}
}
输出-
General Assignment - true
Ternary Assignment - true