1

我想知道递增postpre递减操作。

我在is和isJava之前所知道的。而运算符的关联性是post operatorhighassociativityleft-to-rightpreright-to-left

在此处输入图像描述

Oracle Java 教程

但是我的代码向我显示了不希望的结果-

public class Bunnies { 
    static int count = 3; 
    public static void main(String[] args) { 

        System.out.println(--count*count++*count++);//out put is 12 expected 48
        //associativity of post is higher so should be evaluated like this-

        //--count*3**count++  count is 4 now
        //--count*3*4         count is 5 now
        //4*3*4=48


        count = 3;
        System.out.println(--count*++count*++count); //out put is 24 expected 120
        //associativity of pre  is right to left so should be evaluated like this-

        //--count*++count*4      count is 4 now
        //--count*5*4            count is 5 now
        //4*5*4=120


        count = 3;
        System.out.println(-- count*count++);// out put is 4 expected 9

        //--count*3      count is 4 now
        //3*3=9 
         }
}
4

4 回答 4

3

子表达式的求值顺序与关联性和优先级无关。

乘法的子表达式是从左到右计算的,所以在做的时候--count*count++*count++,你计算--countthencount++和 finally count++

并且由于 pre 运算符首先被评估,--count将在其评估之前递减。同样,由于 post 运算符最近被评估,count++将在其评估后递增。

优先级仅帮助编译器创建正确的抽象语法树。
例如,在执行 时++count*2,编译器使用优先级来知道表达式 is(++count)*2和 not ++(count*2)。同样,在做 时++count*count--,表达式是(++count)*(count--)和非(++(count * count))--或其他。但是,在乘法的评估过程中++count是在评估之前count--

希望这对你有帮助:)

我刚刚在这里找到了关于 C# 和 Java 中表达式评估的一个很好的答案,享受:)

于 2015-05-27T09:55:24.277 回答
1
System.out.println(--count*count++*count++);

= 2 * 2 * 3 = 12

count = 3;
System.out.println(--count*++count*++count) 

= 2*3*4 = 24

count = 3;
System.out.println(-- count*count++);

= 2 * 2 = 4

预增/减

++/-- X首先递增/递减然后执行操作。

后递增/递减

X ++/--首先操作完成,然后递增/递减。

于 2015-05-27T09:39:35.477 回答
0

我拿第一个。

System.out.println(--count*count++*count++);//out put is 12 expected 48
                    2     *    2  * 3 = 12
                    pre   * post  * post
于 2015-05-27T09:40:25.623 回答
0

计数 = 3:

示例 1:

--count*count++*count++ equals (--count)*(count++)*(count++)
(--count) = 2
(count++) = 2 (you increment it AFTER you do something with it)
(count++) = 3 ... count was incremented from before
2*2*3 = 12

示例 2:

--count*++count*++count equals (--count)*(++count)*(++count)
--count = 2
++count = 3
2 * 3 * 3 = 24

示例 3:

(--count)*(count++)
--count = 2
2 * 2 (the count++ gets changed afterwards)

请记住,您必须注意乘法运算符

于 2015-05-27T09:42:21.907 回答