java program using int and double

前端 未结 7 917
礼貌的吻别
礼貌的吻别 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: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
    

提交回复
热议问题