-3

Possible Duplicate:
Why does the division of two integers return 0.0 in Java?

I have some very confusing problem.. I want to calculate some stuff and after some debugging I saw that java calculates this arithmetic: 2 / 4 = 0.0 But it should be 0.5

2 & 4 are stored in integer variables the result is stored in a double-type.

Did I miss something clearly?

Community
  • 1
  • 1
Christian 'fuzi' Orgler
  • 1,682
  • 8
  • 27
  • 51

3 Answers3

7

It is because of integer division (Integer division rounds toward 0). Cast one of the operand to double type.

Example:

double temp = (double)2/4

will give you correct results.

kosa
  • 65,990
  • 13
  • 130
  • 167
4

Use

myDouble = (double) integerWhoseValueIs2 / integerWhoseValueIs4

The fact you store it in a double doesn't change the fact that the division of two integers makes an integer. When you store it, it's too late.

From the Java Language Specification :

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

If you do not write a cast to double, the result is always an int.

double a = (double) 2/4;

andreih
  • 423
  • 1
  • 6
  • 19