This question already has answers here:
Int division: Why is the result of 1/3 == 0?
                                
                                    (15个答案)
                                
                        
                        
                            Division of integers in Java [duplicate]
                                
                                    (7个答案)
                                
                        
                2年前关闭。
            
        

我有以下代码:

float result = (85000/12)*5;
System.out.println(result );


result的值即将到35415.0,但实际计算result为35416.66。

我尝试了所有数据类型,但未获得实际值。我应该如何得到它。

最佳答案

(85000 / 12) * 5;如您所见被评估:85000 / 12以整数算术评估-其余部分被丢弃。其结果乘以5

要保留编译时可评估常量表达式的float类型,请使用85000f / 12 * 5

我总是提倡第一个系数,(i)为了清楚起见,(ii)因为85000 / 12 * 5f之类的东西会表现出截断效果。

09-03 21:12