2025.11.18 Java中float浮点数除以0
浮点数除0不报错
由于IEEE 754 标准的设计特性
public class FloatDivisionTest { public static void main(String[] args) { // 浮点数除零不报错,返回特殊值 float result1 = 1.0f / 0.0f; // Float.POSITIVE_INFINITY float result2 = -1.0f / 0.0f; // Float.NEGATIVE_INFINITY float result3 = 0.0f / 0.0f; // Float.NaN System.out.println("1.0f / 0.0f = " + result1); // Infinity System.out.println("-1.0f / 0.0f = " + result2); // -Infinity System.out.println("0.0f / 0.0f = " + result3); // NaN // 检查特殊值 System.out.println("isInfinite: " + Float.isInfinite(result1)); // true System.out.println("isNaN: " + Float.isNaN(result3)); // true } }
除零返回无穷大或者无穷小,或者时空
而整数的话,就会直接返回除零报错
// 整数除零:运行时立即抛出 ArithmeticException try { int x = 1 / 0; // 抛出 ArithmeticException: / by zero } catch (ArithmeticException e) { System.out.println("整数除零异常: " + e.getMessage()); }
浙公网安备 33010602011771号