java program using int and double

前端 未结 7 860
礼貌的吻别
礼貌的吻别 2020-12-21 00:16

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;
           


        
相关标签:
7条回答
  • 2020-12-21 00:24

    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.

    0 讨论(0)
  • 2020-12-21 00:29

    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;

    0 讨论(0)
  • 2020-12-21 00:32

    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;
    
    0 讨论(0)
  • 2020-12-21 00:36
    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

    0 讨论(0)
  • 2020-12-21 00:37

    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
    
    0 讨论(0)
  • 2020-12-21 00:44

    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);
            }
    
    0 讨论(0)
提交回复
热议问题