Domanda

I am using Java 1.6 final double check = 3 / 4; System.out.println(check);

Console is showing: 0.0

Why is this happening? Shouldn't it come out 0.75?

È stato utile?

Soluzione

Make that:

double check = 3.0 / 4;

and it'll work. You got 0 because 3 / 4 is an integer division, whose value is 0.

Altri suggerimenti

Because both are integer hence result will also be integer.

Cast any one into double like this:

double check = (double)3 / 4;

By doing:

3 / 4

you are performing an integer division, since 3 and 4 are int constants, not doubles. The result is therefore an int. But since you are assigning it to a double, the result of the division will then be promoted to a double. But at this point it is too late, since the integer division will have produced 0!

You need to do:

3.0 / 4

to achieve your desired result, since in this case, 4 will automatically be promoted to a double, and the result of the division will also be a double.

To be perfectly sure of what happens and if you like symmetry, you can also write:

3.0 / 4.0

You are dividing integers and assigning the result to double.In java division of two int values always yields an int.
So change the statement double check = 3 / 4; to double check = 3.0 / 4;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top