理解算术表达式的输出 [英] Understanding the output of an arithmatic expression

查看:124
本文介绍了理解算术表达式的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java类如下:

I have a java class as follows:

class A{
    public static void main(String[] args){
       int a=10;
       a*=a++ +a;
       System.out.println(a);
    }
}

Output:210

在我看来,输出应该 231 计算如下:

In my opinion the output should be 231 calculated as follows:

a*=10+11;
a*=21;
a=a*21;
a=11*21;
a= 231;

任何人都可以解释一下我错在哪里以及为什么?

Can anyone please explain me where am I wrong and why?

推荐答案

在任何类型的陈述中:

x *= y;

在RHS之前评估LHS的初始值。所以你的陈述:

The initial value of the LHS is evaluated before the RHS. So your statement:

a *= a++ + a;

相当于:

a = a * (a++ + a);

将a设置为值10 *(10 + 11)=> 210。

Which sets a to the value 10 * (10 + 11) => 210.

如果您对与此相关的正式规范特别感兴趣,可以找到它这里包含规则如果运算符是复合赋值运算符(第15.26.2节),则评估左手操作数包括记住左手操作数表示的变量和获取并保存该变量的值以用于隐含的二进制操作。

If you're particularly interested in the formal specification related to this point you can find it here which contains the rule "If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation."

这篇关于理解算术表达式的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆