Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 / 2 = 1.0? really? [duplicate]

Tags:

java

android

Possible Duplicate:
Java Integer Division, How do you produce a double?

double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));

Logcat output...

07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0

I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.

like image 217
Paul Blaine Avatar asked Jul 04 '11 08:07

Paul Blaine


1 Answers

In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:

// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f;   // I believe the f and d for float and double are optional, but
double d = 1.0d;  // I wouldn't bet on what the default is if they're omitted...

Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.

To work around this, you should (as many others have suggested) instead calculate the quotient of

(the double 3) / (the double 2)

or, in Java syntax,

double wang = 3.0 / 2.0;

1 Source: The Java Tutorial from Oracle

like image 183
Tomas Aschan Avatar answered Sep 20 '22 14:09

Tomas Aschan