tags:

views:

112

answers:

4

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+number/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
+8  A: 

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.

Felix Kling
+2  A: 

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

jk
+1  A: 

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.

Edan Maor
-1 - `rot*=100+number/10;` is NOT the same as `rot * 100 + number / 10;` and `rot * 100 + number / 10;` is NOT the same as `rot * (100 + (number / 10));`. You got the right answer, but for the wrong reason.
Stephen C
@Stephen: Thanks, I've changed my answer to what I think is the correct one (just removed the second step, since it was wrong... not sure what I was trying to say with it).
Edan Maor
A: 

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).

GK