在post ++和--pre运算符上运算

时间:2015-05-27 09:35:38

标签: java operators operator-precedence associativity

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

Java post operator的{​​{1}}优先级high associativityleft-to-right的{​​{1}} pre right-to-left运算符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 } } 1}}

enter image description here

Oracle Java Tutorial

但我的代码显示了不受欢迎的结果 -

instance (using the "getParagraphs()" method)

4 个答案:

答案 0 :(得分:3)

  

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

乘法的子表达式从左到右进行评估,因此在执行--count*count++*count++时,您评估--count然后评估count++,最后评估count++

首先评估pre运算符,--count将在评估之前递减。同样,由于最近评估了后期运算符,count++将在评估后递增。

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

希望这可以帮助你:)

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

答案 1 :(得分: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 ++/--首先完成操作,然后递增/递减。

答案 2 :(得分:0)

我拿第一个。

System.out.println(--count*count++*count++);//out put is 12 expected 48
                    2     *    2  * 3 = 12
                    pre   * post  * post

答案 3 :(得分:0)

count = 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)

请记住,您必须观看乘数运算符