gpt4 book ai didi

java - Math.min() 中后递增运算符的有趣行为

转载 作者:行者123 更新时间:2023-12-01 18:57:17 24 4
gpt4 key购买 nike

我有一个问题,
JavaMath.min++ 绑得更紧?
让我用一个例子来说明,也许有人可以向我解释为什么我会得到这样的结果。

这是我运行的方法:

private static void testIncrement() {
int x=10;
System.out.println(x++);
System.out.println(x);

x=10;
System.out.println("-----------");
System.out.println(++x);
System.out.println(x);

x=10;
System.out.println("-----------\n"+x); //10
x=Math.min(255, x++);
System.out.println(x); **//x=10 WHY NOT x=11?**

x=10;
System.out.println("-----------\n"+x);
x=Math.min(255, ++x);
System.out.println(x);
}

结果是:

10
11
-----------
11
11
-----------
10
10
-----------
10
11

在我放置 //x=10 WHY NOT x=11? 的行上
我想知道为什么x是 10 而不是 11。也许有人可以向我解释一下。

看起来好像 Math.min创建 x 的副本(此时为 10)它用来做什么 Math.min 。然后原来的x从 10 增加到 11,但仍为 10 的副本来自 Math.min并覆盖增加的值。

这有道理吗?有谁能解释一下为什么在这种情况下 x 是 10 而不是 11?

谢谢

PS - 我完全理解How do the post increment (i++) and pre increment (++i) operators work in Java?

最佳答案

让我们解构这一行:

x = Math.min(255, x++); 

x++ 的意思是“记住x的原始值;然后递增x;然后表达式的值就是原始值” 。所有这些都发生在分配之前。所以它相当于:

int tmp = x;               // x = 10, tmp = 10
x = x + 1; // x = 11, tmp = 10
x = Math.min(255, tmp); // x = 10

希望这应该能说明问题。特别是,这与 Math.min 本身无关 - 它只是表现为正常的方法调用。请参阅section 15.14.2 of the JLS了解更多详情。

关于java - Math.min() 中后递增运算符的有趣行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com