I have written a simple Java program as shown here:
public class Test {
public static void main(String[] args) {
int i1 =2;
int i2=5;
double d = 3 + i1/i2 +2;
System.out.println(d);
}
}
Since variable d
is declared as double I am expecting the result of this program is 5.4
but I got the output as 5.0
Please help me in understanding this.
i1/i2
will be 0. Since i1
and i2
are both integers.
If you have int1/int2
, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5
is 0.4, so you'll get 0.
You can cast i1
or i2
to double
(the other will be implicitly converted)
double d = 3 + (double)i1/i2 +2;
i1/i2
when converted to int gives 0. ie. why you are getting 5.0. Try this :
public static void main(String args[])
{
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
System.out.println(d);
}
This line is done in parts:
double d = 3 + i1/i2 +2;
double d = 3 + (i1/i2) +2;
double d = 3 + ((int)2/(int)3) +2;
double d = 3 + ((int)0) +2;
double d = (int)5;
double d = 5;
The double just means that the answer will be cast to a double, it doesn't have any effect till the answer is computed. You should write
double d = 3d + (double)i1/i2 +2d; //having one double in each "part" of the calculation will force it to use double maths, 3d and 2d are optional
i1/i2
will be 0 because both i1
and 12
are integers.
if you cast i1
or i2
to double
then it will give the desired output.
double d = 3 + (double)i1/i2 +2;
This link provides information about data type conversion, both implicit and explicit type.
To provide exact answer to the question will be :
double d = 3 + (double)i1/i2 + 2
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
if i1/i2 will be fractional value then double will help it to be in fraction instead of int.
so now you will the result as you want. or you can also use following code
double d = 3+(double)i1/i2+2;
In this line i1 is converted into double which will be divided with i2 and result will be in double, so again result will be as 5.4
Since i1=2 and i2=5 are integer type and when you divide (2/5) them, It gives integer value (0) because fractional part(.4) get discarded.
So put (double)i1/i2 on the equation.