1

インクリメントとデクリメント操作postで疑問に思っています。pre

isとisJavaの優先順位で私が知っていること.while演算子の結合性は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

部分式の評価順序は、結合性と優先順位の両方から独立しています。

乗算の部分式は左から右に評価されるため、 を実行するときはthen--count*count++*count++を評価し、finallyを評価します。--countcount++count++

また、pre 演算子が最初に評価さ--countれると、その評価の前にデクリメントされます。同様に、post 演算子は最近評価さcount++れるため、評価後にインクリメントされます。

優先順位は、コンパイラが正しい抽象構文ツリーを作成するのに役立つだけです。
たとえば、 を実行する場合++count*2、コンパイラは優先順位を使用して、式が is(++count)*2であり、 notであることを認識し++(count*2)ます。同様に、 を実行する場合++count*count--、式は is (++count)*(count--)and not(++(count * count))--またはwhatever です。しかし、その後、乗算の評価中に、 の++count前に評価されcount--ます。

これがお役に立てば幸いです:)

ここで C# と Java での式の評価に関する素晴らしい回答を見つけました。お楽しみください :)

于 2015-05-27T09:55:24.277 に答える
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 に答える