如何评估Java运算符的求值

huangapple go评论80阅读模式
英文:

How to evaluate the java operators evaluation

问题

我是Java新手,正在尝试理解计算步骤是如何执行以达到最终结果的。最终答案是49。根据运算符的优先级,我的计算结果不是49。

以下是我的代码和表达式:

class Test
{
  public static void main(String args[])
  {
   int a = 6, b = 5;
   a = a + a++ % b++ * a + b++ * --b;
   System.out.print(a);
  }

}

希望这可以帮助你理解代码的运行结果。

英文:

I am java newbie and trying to understand how calculation steps are performed to achieve final result. The final answer is coming as 49. Looking at precedence operators hierarchy my calculation is not coming to 49.

Following is my code with expression:

class Test
{
  public static void main(String args[])
  {
   int a = 6, b = 5;
   a = a + a++ % b++ *a + b++ * --b;
   System.out.print(a)
  }

} 

答案1

得分: 0

操作符有优先级。可以在这里找到一个表格(链接:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)。

另外,您可以使用圆括号(括号)来强制执行正确的计算顺序。

英文:

Operators have priorities. There is a table of these here.

Also, you can use round brackets (parentheses) for forcing the right sequence of calculations.

答案2

得分: 0

取模运算与除法和乘法具有相同的优先级。下一个优先级是加法和减法。操作从左到右进行。

为了更清晰,添加括号:

      ( a ) + ( a++ % b++ *a ) + ( b++ * --b )
组     I         II                 III
  1. a++ % b++ *a 计算如下:a. (6 % 5) = 1
    b. 1 * 6 到目前为止,a = 6,b = 5

完成此操作后,a 和 b 的值分别增加到 7 和 6。即后缀递增仅在模数/乘法/除法在步骤或组中完成后发生,如上所示。

  1. b++ * --b => 6 * 6。得到值为 36
    完成此操作后,执行 ++ 操作,但也执行了 -- 操作,有效地将 b 的值保留为 6。

  2. 下一个操作是加法。即 7 + 6 + 36 = 49

参考链接:https://www.programiz.com/java-programming/operator-precedence

英文:

Modulo has same precedence as division and multiplication. The next precedence goes to addition and subtraction.Operations happen left to right.

Adding brackets for better clarity:

      ( a ) + ( a++ % b++ *a ) + ( b++ * --b )
group   I         II                 III
  1. a++ % b++ *a evaluated as :a. (6 % 5) = 1
    b. 1 * 6 till now, a = 6, b = 5

Having completed this operation, the value of a & b are incremented to 7 & 6 respectively. i.e the post fix increment happens only after the modulo/multiplication/division during a step or group as shown above.

  1. b++ * --b => 6 * 6. gives value of 36
    Having completed this operation the ++ operation is performed but -- is also performed, effectively leaving the value of b at 6.

  2. next operation is addition. i.e 7 + 6 + 36 = 49

Reference: https://www.programiz.com/java-programming/operator-precedence

huangapple
  • 本文由 发表于 2020年10月2日 22:46:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64173569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定