簡體   English   中英

Java中的增量和減量運算符

[英]Increment and Decrement operators in java

我對增量和減量運算符有疑問。我不明白為什么Java會給出這些輸出。

    x = 5;  y = 10;
    System.out.println(z = y *= x++); // output is 50
    x = 2; y = 3; z = 4;
    System.out.println("Result = "+ z + y++ * x); // output is Result = 46
    x = 5;
    System.out.println( x++*x); // output is 30
    x = 5;
    System.out.println( x*x++); // output is 25

例如,在第二個println函數中,y乘以而不增加1,而在第三個函數中,x函數與x + 1乘。 據我所知,一元增和一元減運算符的優先級高於算術運算符,那么為什么第二個運算符不增加1(y ++ * x = 3 * 2 = 6)而為什么(y + 1)* x = 8呢?

需要了解的內容:

后遞增運算符(變量名后的++ )返回變量的值,然后遞增變量。 因此,如果x5 ,則表達式x++計算結果為5並且副作用是x設置為6

這個有點特別:

x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46

請注意,此處使用了字符串連接 它輸出Result = ,然后輸出4 ,即z的值,然后輸出y++ * x的值6 46不是一個數字,它是來自兩個表達式的46

 x = 5;  y = 10;
    System.out.println(z = y *= x++); // output is 50 -->z=y=y*x i.e, z=y=10*5 (now, after evaluation of the expression, x is incremented to 6)
    x = 2; y = 3; z = 4;
    System.out.println("Result = "+ z + y++ * x); // output is Result = 46 --> from Right to left . y++ * x happens first..So, 3 * 2 = 6 (now, y will be incremented to 4) then "Result = " +z (String) + number (y++ * z) will be concatenated as Strings.
    x = 5;
    System.out.println( x++*x); // output is 30 --> 5 * (5+1 i.e, x is already incremented to 6 when you do x++ so its like 5 *6 )
    x = 5;
    System.out.println( x*x++); // output is 25 -- > 5 * 5 (x will be incremented now)

postfix- ++表示,該變量以其當前值求值,並且在對周圍的表達式求值后,該變量遞增。

y ++將在代碼后向y加1。 ++ y將在代碼之前將y加1。

它們的優先級高於二進制運算符,但它們的取值為'x'。 后遞增的副作用不是優先考慮的部分。

因為使用y++ y將首先被評估,然后被遞增。

相反,對於++y ,增量在評估之前發生。

您的第一個表達式z = y *= x++等於:

z=y=y*x;
x++;

您的第二個表達式+ z + y++ * x等效於此:

z + ""+ (y*x) // here z = 4 and y*x is 6 which gives us 46.

同樣,您可以找到第三和第四表達。

我建議閱讀本教程,我認為這將使用法-> Java運算符更加清晰

讓我們把它放在碎片上:

x = 5;  y = 10;
System.out.println(z = y *= x++);

在上面的代碼中,您將y * = x ++的結果分配給z; 這意味着y = y * x ++。 現在,x ++將在乘法完成后求值。 如果您希望它以前發生過,則應該使用++ x。

x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46

在這種情況下,您可以將字符串與上述值連接起來; 將首先進行乘法運算,然后再進行加法運算,直到最后才計算后增量。

其余示例與上述示例相似。 運算符優先級是上面應用的規則,您可以使用此表查看評估它們的順序: 運算符優先級

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM