7

I'm a high school student currently getting ready for a state academic meet(UIL). I have a problem and I've looked everywhere and can't seem to find an answer! Why does this print out 0.0?

double d = 1/2;
System.out.println(d);
Maljam
  • 6,244
  • 3
  • 17
  • 30
Benton Justice
  • 111
  • 1
  • 2
  • 7

4 Answers4

17

It's because of the data type.

When you do 1/2 that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero).

If you convert any one of them to double, you'll get a double result.

double d = 1d/2;

or

double d = 1/2.0;
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

1 and 2 are both integers, so 1 / 2 == 0. The result doesn't get converted to double until it's assigned to the variable, but by then it's too late. If you want to do float division, do 1.0 / 2.

shmosel
  • 49,289
  • 6
  • 73
  • 138
2

It's because 1 and 2 are int values, so as per the java language spec, the result of an arithmetic operation on int operands is also int. Any non-whole number part of the result is discarded - ie the decimal part is truncated, 0.5 -> 0

There is an automatic widening cast from int to double when the value is assigned to d, but cast is done on the int result, which is a whole number 0.

If "fix" the problem, make one of the operands double by adding a "d" to the numeric literal:

double d = 1d/2;
System.out.println(d); // "0.5"

As per the language spec, when one of the operands of an arithmetic operation is double, the result is also double.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Cause result of 1/2 = 0 and then result is parsing to double. You're using int instead of double. I think it should be ok:

double d = 1/2.0;
System.out.println(d);

Sorry for weak english

Krulig
  • 11
  • 1