I was interested to see a weird error when performing the following:
int width = 300;
int var1 = width/3;
int var2 = width * 1/3;
int var3 = width * 2/3;
int var4 = width*(1/3);
int var5 = width * (int)(1/3);
int var6 = (int)(width*(1/3));
System.out.println("Var1: " + var1);
System.out.println("Var2: " + var2);
System.out.println("Var3: " + var3);
System.out.println("Var4: " + var4);
System.out.println("Var5: " + var5);
System.out.println("Var6: " + var6);
Output is this:
Var1: 100
Var2: 100
Var3: 200
Var4: 0
Var5: 0
Var6: 0
Why do the last three operations return 0
? The parenthesis around the 1/3
seems to change something with how it performs the calculation, but even trying to case it into an int
did not change the output.
I'm using the BlueJ IDE
and Java version 1.7.0_17
EDIT
I found the answer. It's due to the order of operation. The parens
cause the division to occur first, and with an int
1/3 or 2/3 will always equal 0
. If I allow the width * 2
to occur before dividing by 3
everything is OK because the number is larger than 1
.
Sometimes it's just basic math... :)