【问题标题】: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

【问题讨论】:

  • 括号我的朋友括号。记住 BODMAS

标签: 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+1assignmentincrement 操作的顺序之间只有区别。

    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);
        }
    

    我会建议你使用括号,因为它也会增加可读性。

    【讨论】:

    • 第一个是 12,第二个是 11 no
    猜你喜欢
    • 1970-01-01
    • 2022-10-31
    • 2017-01-11
    • 2020-02-06
    • 2013-06-10
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多