3

Here's the code:

class testsum
{ 
    public static void main(String arg[]) 
    {
        double sum=0; 
        double fraction;
        fraction=-1/9;
        System.out.println("fraction: "+fraction); 
        fraction=-1; 
        fraction=fraction/9; 
        System.out.println("fraction: "+fraction); 
    } 
} 

the outputs are 0 and then -0.11111111

why was the first output 0 and not -0.11111111111?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
David
  • 14,569
  • 34
  • 78
  • 107

6 Answers6

8

It's doing integer division in the first example as this is the default type for a numeric literal. Try changing it to -1.0/9 (or 1d/9d - the d suffix indicates a double) and you should get the same answer.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
  • so it does integer division even though the value is going to be stored in a variable of type double? – David Apr 04 '11 at 20:03
  • 1
    The division happens before it knows it's going to be a double. It does the division in integer, and then realizes it has to be converted to a double. This has been the source of many bugs since epoch. – corsiKa Apr 04 '11 at 20:04
  • Yes, it doesn't take that into account (rightly or wrongly!) – Jeff Foster Apr 04 '11 at 20:04
2

1 and 9 are both integer. Try

1.0/9

This is why it works for fraction/9, since fraction is a double.

Gustav Larsson
  • 8,199
  • 3
  • 31
  • 51
1

When you do -1/9, it says "-1, that's an int. 9, that's an int. -1 / 9 in integer division is 0. Oh, now I need to cast to double."

Changing it to -1.0 / 9 should solve the problem.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
0

Try wrapping the "-1/9" in brackets.

Chris Bornhoft
  • 4,195
  • 4
  • 37
  • 55
0

The first one is 0 because it is doing integer division. -1 and 9 and integers and when divided equal 0. The result is then converted into a double so it can be stored in fraction. The easiest solution is this:

fraction = -1.0/9;
unholysampler
  • 17,141
  • 7
  • 47
  • 64
0

Because -1 and 9 are integers, so -1/9 is an integer division (with the result 0, which when cast to double is 0.0).

To do a floating point division, you should convert one of the numbers to double, (double) 9, 9d or simply 9.0.

In the latter case, fraction is already double (-1.0) so fraction/9 is a floating point division.

aib
  • 45,516
  • 10
  • 73
  • 79