-2

OK so this is a problem in a larger piece of code which does'nt seem to make sense. below is the code which is the problem... It prints Ratio = 0.0 the console when launched it should be equal to ~0,348.

public class MathTest {

    public static void main(String[] args) {

        double ratio = 29511 / 84812;
        System.out.println("Ratio = "+ ratio);

    }

}

Edit:

What if the code is this:

public class MathTest {

    public static void main(String[] args) {
        int int1 = 7;
        int int2 = 13;
        double double1 = int1/int2;
        System.out.println("double1 = "+ double1);

    }

}

It again prints "0.0".

4 Answers4

6

You have unwittingly used integer division when you say 29511 / 84812, which in Java, loses the decimal points. Use double literals (with .0 added) instead:

double ratio = 29511.0 / 84812.0;

Other solutions that work here:

  • Cast one of them to a double: (double) 29511 / 84812
  • Use 'D' as another way to indicate a Java double literal: 29511D / 84812D
rgettman
  • 167,281
  • 27
  • 248
  • 326
3

You are doing integer division because 29511 and 84812 are ints. The result of the division is 0, and you are saving it as a double so it becomes 0.0.

To fix this, cast one of the operands on the right side of the assignment to a double.

double ratio = (double)29511 / 84812;
Colin D
  • 5,400
  • 1
  • 21
  • 35
0

Replace double ratio = 29511 / 84812 with double ratio = 29511.0 / 84812.0;

Adam Siemion
  • 14,533
  • 4
  • 47
  • 84
0

It make perfect sense. You are dividing two integers to get an integer. This means 0 in this case.

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075