【问题标题】:Java: Order of Operations, Post-Increment ClarificationJava:操作顺序,增量后澄清
【发布时间】:2021-10-25 18:06:48
【问题描述】:

为什么输出是 25?

// CODE 1
public class YourClassNameHere {
    public static void main(String[] args) {
      int x = 8;
      System.out.print(x + x++ + x);
    }
}

嗨!

我知道上面的代码将打印 25。但是,我想澄清一下 x++ 将如何使语句为 8 + 9 + 8 = 25。

如果我们只打印 x++,则将打印 8,而 x 将在内存中打印 9,因为后递增。

// CODE 2
public class YourClassNameHere {
    public static void main(String[] args) {
      int x = 8;
      System.out.print(x++);
    }
}

但为什么在代码 1 中它最终变成了 9?

提前感谢您的时间和解释!

【问题讨论】:

    标签: java syntax increment post-increment pre-increment


    【解决方案1】:

    这里有一个很好的方法来测试等于25的原因是因为第三个x等于9。

    public class Main {
    
        public static void main(String[] args) {
            int x = 8;
            System.out.println(printPassThrough(x, "first") + printPassThrough(x++, "second") + printPassThrough(x, "third"));
        }
    
        private static int printPassThrough(int x, String name) {
            System.out.println(x + " => " + name);
            return x;
        }
    }
    

    结果

    8 => first
    8 => second
    9 => third
    25
    

    【讨论】:

    • 哇,这真是一个很棒的答案!无聊也可以看看我的!
    • @TimBiegeleisen 也感谢蒂姆的崩溃!更新了你的两个回复!
    • @Sam 您可能会考虑将字符串作为printPassThrough 的第二个参数并包含在 println 中,因此评估顺序很明显。例如。 printPassThrough(x, "first") => 8 first.
    • @AndyTurner 已根据您的建议进行了编辑。
    • 得到8+9+8的数序,表达式应该是这样的: System.out.println(print(x, "->first") + print(++x, "->第一个") + print(--x, "->第三个"));
    【解决方案2】:

    我认为值得澄清:

    x++ -> 对 x 进行运算,然后将 x 加一(即 x=x+1)

    ++x -> 递增x(表示x=x+1),然后操作x

    x---> 对 x 进行运算,然后将 x 递减(即 x=x-1)

    --x -> 递减x(表示x=x-1),然后对x进行操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2014-04-11
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 2018-10-09
      相关资源
      最近更新 更多