1

Unlike many of the other posts I am wanting to find out why my code is automatically rounding down to the nearest whole number??

See code here

    double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

See the output here:

Sixes: 66.0

Threes: 33.0

These should both be 66.66666666666 and 33.3333333333 respectively but I am not sure why they are being rounded down?

Steffen Harbich
  • 2,269
  • 1
  • 29
  • 60
SHooper
  • 38
  • 7

2 Answers2

1

The question is whether you add a decimal point after the number, if you don't add it be double is divided by int and not double divided be double , here examples :

Double divied by int :

   double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

Output :

Sixes: 66.0
Threes: 33.0

Double divied by double:

   double sixes = 200/3.0;
    double threes = 100/3.0;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

Output :

Sixes: 66.66666666666667
Threes: 33.333333333333336
Pluto
  • 829
  • 1
  • 5
  • 23
0

The algorithm depends on the most complex argument. You calculate integer numbers, therefore an algorithm is used that produces integer as output. Finally that integer gets implicitly converted to double to fit into your variable.

Try double sixes = 200.0/3.0;to verify that.

Stefan
  • 1,645
  • 1
  • 10
  • 15