gpt4 book ai didi

java - Java 后递增器的行为

转载 作者:行者123 更新时间:2023-12-01 18:41:03 27 4
gpt4 key购买 nike

    public static void main(String[] args) {
int a = 1;
int b = a++;

System.out.println(b);
}

为什么上面的代码打印1?有人告诉我 a++ 意味着你会得到 a 的值。然后增加它。但上面的代码从未增加 a 并只是打印 1。有人可以解释一下这里发生了什么吗?

最佳答案

它按预期工作;代码解释如下:

public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// b is assigned the value of a (1) and THEN a is incremented.
// b is now 1 and a is 2.
int b = a++;

System.out.println(b);
// if you had printed a here it would have been 2
}

这是相同的代码,但预先递增了 a:

public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// a is incremented (now 2) and THEN b is assigned the value of a (2)
// b is now 2 and so is a.
int b = ++a;

System.out.println(b);
// if you had printed a here it would have been 2 so is b.
}

关于java - Java 后递增器的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19970114/

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