Java problem (Spidey?)

5 posts / 0 new
Last post
SAS_Leon
Veteran
Veteran
Offline
Last seen: 5 years 6 months ago
Java problem (Spidey?)

I stumbled upon this Java program line which is just simple arithmetic... but I don't understand why the outcome is 6, when it "should" be 5.25.

This is the program:

public class Test
{
public static void main(String args [])
{
System.out.println( (3+1)/2*3 - 3/(1+3) );
}
}

When I run this program in command window, the program prints 6. On the calculator the answer is 5.25.

SAS_Relish
Veteran
Veteran
Offline
Last seen: 5 years 11 months ago

3/(1+3) = 0

integer / integer gives you an intger. In the case it does not come out as a complete integer it rounds down. In this case from 0.75 to 0.0.

Put a double in there and you will be fine.

eg. 3.0/(1+3) = 0.75

Oh and hello everyone hows everyone doing.

SAS_Vet_Relish

Spidey01
Offline
Last seen: 3 months 1 week ago

Why I had no idea you know the difference between an Integar and a FPN Relish Smile

Howdy m8.

SAS_Leon
Veteran
Veteran
Offline
Last seen: 5 years 6 months ago

Ah, I see. Thanks Relish :).
They are int as default of course, and not floating-point numbers.

Spidey01
Offline
Last seen: 3 months 1 week ago

http://mathworld.wolfram.com/IntegerDivision.html

I usually will use a float or a double for a number if I'm not sure it will be a whole number. Like my exit status or a simple on/off switch.