This question already has answers here:
Double division behaving wrongly
                                
                                    (4个答案)
                                
                        
                5年前关闭。
            
        

我目前有以下代码:

    int kills = 1;
    int deaths = 2;

    double kdr = 0;

    if(kills > 0 && deaths == 0) {
        kdr = kills;
    } else if(kills > 0 && deaths > 0){
        kdr = kills/deaths;
    }

    System.out.println(kdr);


您可以here对其进行测试。

为什么输出0.00,而不是0.5?

最佳答案

如果kills/deaths 0,因为整数除法的输出是整数。然后将此0强制转换为0.0以适合存储它的double变量。

为了获得非整数结果,您必须将数字之一强制转换为double:

 kdr = (double)kills/deaths;

09-11 19:57