开发者

Arithmetic operator confusion

开发者 https://www.devze.com 2022-12-15 23:22 出处:网络
Why I\'m getting two different values while using the arithmetic operators for the same value of variables. I\'ve just altered little bit my second program, which is resulted in giving me the differen

Why I'm getting two different values while using the arithmetic operators for the same value of variables. I've just altered little bit my second program, which is resulted in giving me the different output. Could anyone please tell me why?

    int number=113;
 int rot=0;
 rot=number%10;
 rot*=100+numbe开发者_StackOverflow社区r/10;
 System.out.println(rot);//333



    int number=113;
 int rot=0;
 rot=number%10;
 rot=rot*100+number/10;
 System.out.println(rot);//311


In the first part you compute

rot *= 100 + number/10

which is

rot = rot * (100 + number/10)

And in the second part:

rot = rot*100 + number/10

Note that multiplication and division goes before addition and substraction.


the problem is that *= has different (lower) precedence than * and +

rot *= 100 + number/10;

is equavalent to

rot = rot * (100 + number /10);

operator precdence can be found here


It seems like the problem is operator precedence.

What this means is that num * 10 + 13 is treated like (num * 10) + 13, i.e. the () are automatically added according to the rules of the language.

The difference then, in your example, is that the first one means the following:

rot*=100+number/10;
// Is the same as this:
rot = rot * (100 + (number / 10));

Whereas the second one means the following:

rot=rot*100+number/10;
// Is the same as this:
rot = (rot * 100) + (number / 10);

Since the parenthesis are in different places, these probably evaluate to different numbers.


in the second code because of the high precedence of *. rot*100 will be calculated and to that (number/10) will be added so its (300 + 11 = 311).

0

精彩评论

暂无评论...
验证码 换一张
取 消