Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 1 / 2 == 0 using double? [duplicate]

Tags:

java

double

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);
like image 242
Benton Justice Avatar asked Apr 27 '16 23:04

Benton Justice


1 Answers

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;
like image 60
Suresh Atta Avatar answered Oct 04 '22 13:10

Suresh Atta