【问题标题】:How do I use increment in calculations?如何在计算中使用增量?
【发布时间】:2015-07-20 01:14:36
【问题描述】:
{int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);} //12
编译器给出了 num3 = 12,但我如何获得该值?当我尝试获得 num3 值时,我得到了 6(不使用编译器)。 num2++ 和 ++num2 的值都相同,但是当我使用以下代码时,它会给出不同的值。为什么我得到不同的价值观。获取这些 num3 值的步骤是什么(不使用编译器?)
num3 = num2++ * num1 / num2 + num2; //11
【问题讨论】:
标签:
java
post-increment
pre-increment
【解决方案1】:
如果你这样做:
int num2 = 6;
System.out.println(num2++);
它将打印 6,然后将 num2 更改为 7。但如果你这样做:
int num2 = 6;
System.out.println(++num2);
它会将 num2 更改为 7,然后打印 7。所以:
num3 = ++num2 * num1 / num2 + num2;
num3 = 7 * 5/ 7 + 7
num3 = 35/7 + 7
num3 = 12
【解决方案2】:
num++ 和 ++num 的递增操作都将导致 num=num+1,assignment 和 increment 操作的顺序之间只有区别。
num++(post-increment) -> first num is used and then incremented
++num(pre-increment) -> first num is incremented and then used
当我测试时,您的代码打印 12。
public static void main(String[] args) {
int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);
}
我会建议你使用括号,因为它也会增加可读性。