Java program using int and double

I wrote 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 the variable d declared as double, I expect the result of this program is 5.4 , but I got the result as 5.0

Please help me in understanding this.

+4
source share
7 answers

i1/i2 will be 0. Since i1 and i2 are integers.

If you have int1/int2 , if the answer is not a perfect integer, the digits after the decimal point will be deleted. In your case, 2/5 is 0.4, so you get 0.

You can apply i1 or i2 to double (the other will be implicitly converted)

double d = 3 + (double)i1/i2 +2;

+11
source

i1/i2 when converting to int gives 0. ie. why you get 5.0. Try the following:

  public static void main(String args[]) { int i1 =2; int i2=5; double d = 3 + (double)i1/(double)i2 +2; System.out.println(d); } 
+5
source

This line is executed 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; 

A double simply means that the response will be passed to double, it will have no effect until the answer is calculated. You have to 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 
+3
source

i1/i2 will be 0, since both i1 and 12 are integers.

if you added i1 or i2 to double , then it will give the desired result.

 double d = 3 + (double)i1/i2 +2; 
+2
source

This link contains information about data type conversion, both implicit and explicit type.

For an accurate answer to the question will be:

 double d = 3 + (double)i1/i2 + 2 
+1
source
 int i1 =2; int i2=5; double d = 3 + (double)i1/(double)i2 +2; 

if i1 / i2 is a fractional value, then double will help it to be in the fraction instead of int. so now you get the result on your own. or you can also use the following code double d = 3+ (double) i1 / i2 + 2; In this line, i1 is converted to double, which will be divided by i2, and the result will be doubled, so the result will be 5.4

+1
source

Since i1 = 2 and i2 = 5 are integer types, and when you divide (2/5) them, it gives an integer value (0), because the fractional part (.4) is discarded. So, put (double) i1 / i2 on the equation.

0
source

All Articles