Java中Math.round(VALUE)与(int) VALUE的区别详解(Python转Java开发者)
Java中
Math.round(VALUE)与(int)强制类型转换的区别 核心逻辑差异
(int)强制转换:直接丢弃小数部分,只保留整数位,和你熟悉的Pythonint(VALUE)行为完全一致。例子:(int)2.9→2(int)-2.9→-2
Math.round(VALUE):执行四舍五入,将数值近似到最近的整数。如果小数部分恰好是0.5,会向正无穷方向取整。例子:Math.round(2.9)→3Math.round(2.5)→3Math.round(-2.9)→-3Math.round(-2.5)→-2
返回值类型区别
(int)强制转换的结果直接是int类型。Math.round()的返回值分两种情况:传入float时返回int,传入double时返回long,如果需要int类型得手动强转,比如(int)Math.round(2.9)。
代码示例对比
public class RoundTest { public static void main(String[] args) { double posNum = 2.9; double posHalf = 2.5; double negNum = -2.9; double negHalf = -2.5; // 强制转换输出 System.out.println("(int)2.9 = " + (int)posNum); // 2 System.out.println("(int)-2.9 = " + (int)negNum); // -2 // Math.round输出 System.out.println("Math.round(2.9) = " + Math.round(posNum)); // 3 System.out.println("Math.round(2.5) = " + Math.round(posHalf)); // 3 System.out.println("Math.round(-2.9) = " + Math.round(negNum)); // -3 System.out.println("Math.round(-2.5) = " + Math.round(negHalf)); // -2 } }
和Python操作的对应关系
Java的(int)强制转换完全对应Python的int(VALUE),都是截断小数。而Python中类似Math.round()的四舍五入是round(VALUE),但注意两者在0.5的处理上有差异:Python的round(2.5)返回2、round(-2.5)返回-2(向偶数取整),Java则是向正无穷取整。
内容的提问来源于stack exchange,提问作者AFT
相关产品推荐
相关产品推荐

