数学表达式的正确优先顺序是什么 [英] What is the right precedence of the math expression
问题描述
在此Java表达式中,数学运算的正确顺序是什么?
What is the correct sequence of the math operations in this expression in Java:
a + b * c / ( d - e )
1. 4 1 3 2
2. 4 2 3 1
我知道两个答案的结果是相同的.但是我想充分理解java编译器的逻辑.在此示例中,首先执行的是乘法或括号中的表达式?包含相关说明的文档链接.
I understand that result is the same in both answers. But I would like to fully understand the java compiler logic. What is executed first in this example - multiplication or the expression in parentheses? A link to the documentation that covers that would be helpful.
更新:谢谢大家的回答.你们中的大多数人都写道,括号中的表达式首先被求值.在查看了Grodriguez提供的参考之后,我创建了一些测试:
UPDATE: Thank you guys for the answers. Most of you write that the expression in parentheses is evaluated first. After looking at the references provided by Grodriguez I created little tests:
int i = 2;
System.out.println(i * (i=3)); // prints '6'
int j = 2;
System.out.println((j=3) * j); // prints '9'
有人可以解释为什么这些测试产生不同的结果吗?如果首先对括号中的表达式求值,我会期望得到相同的结果-9.
Could anybody explain why these tests produce different results? If the expression in parentheses is evaluated the first I would expect the same result - 9.
推荐答案
到目前为止,几乎所有人都对运算符优先级的求值顺序感到困惑.在Java中,优先级规则使表达式等同于以下内容:
Almost everybody so far has confused order of evaluation with operator precedence. In Java the precedence rules make the expression equivalent to the following:
a + (b * c) / ( d - e )
因为*
和/
具有相同的优先级,并且保持关联性.
because *
and /
have equal precedence and are left associative.
评估顺序严格定义为首先是左操作数,然后是右操作数,然后是(||和&&除外).因此,评估顺序为:
The order of evaluation is strictly defined as left hand operand first, then right, then operation (except for || and &&). So the order of evaluation is:
a
b
c
*
d
e
-
/
+
评估顺序在页面上.缩进反映了语法树的结构
order of evaluation goes down the page. Indentation reflects the structure of the syntax tree
修改
回应Grodriguez的评论.以下程序:
In response to Grodriguez's comments. The following program:
public class Precedence
{
private static int a()
{
System.out.println("a");
return 1;
}
private static int b()
{
System.out.println("b");
return 2;
}
private static int c()
{
System.out.println("c");
return 3;
}
private static int d()
{
System.out.println("d");
return 4;
}
private static int e()
{
System.out.println("e");
return 5;
}
public static void main(String[] args)
{
int x = a() + b() * c() / (d() - e());
System.out.println(x);
}
}
产生输出
a
b
c
d
e
-5
清楚地表明乘法是在减法之前 执行的.
which clearly shows the multiplication is performed before the subtraction.
这篇关于数学表达式的正确优先顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!