This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
Explanation to what's happening:
In Java, the default type of numbers is
int
, so when you write50/110000
, they're both consideredint
, although you defined the result to bedouble
.When
int
division occurs, the result will be0
, because they are bothint
s, then thedouble
will hold this value, which will be represented asdouble
, so you're getting0.000000
.Possible solutions:
d
:50d/110000d
.(double)50/110000
.50.0/110000
.See Chapter 5. Conversions and Promotions, it'll really help you.
Because you're dividing two integers, so it will only take the integer part (integer division).
Examples :
You can cast one of the number (or both but it's actually useless) to
double
to avoid that :Result of
int/int
returns you aninteger
.So the decimal part got truncated resulting you with an integer
You need to cast:
As @Josh M has pointed, You can also try :