为什么整数除以零 1/0 会出错,但浮点数 1/0.0 返回“Inf"? [英] Why does integer division by zero 1/0 give error but floating point 1/0.0 returns "Inf"?

查看:27
本文介绍了为什么整数除以零 1/0 会出错,但浮点数 1/0.0 返回“Inf"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是对此感到好奇:

在 Java 中计算 1/0 时,会出现以下异常:

When evaluating 1/0 in Java, the following exception occurs:

线程main"中的异常java.lang.ArithmeticException:/by零在 Foo.main(Foo.java:3)

Exception in thread "main" java.lang.ArithmeticException: / by zero at Foo.main(Foo.java:3)

但是 1/0.0 被评估为 Infinity.

public class Foo {
    public static void main (String[] args) {
        System.out.println(1/0.0);
    }
}

为什么会这样?

推荐答案

这是因为整数没有 +/-Inf、NaN 的值,并且不允许除以 0,而浮点数却有这些特殊值.

That's because integers don't have values for +/-Inf, NaN, and don't allow division by 0, while floats do have those special values.

这篇关于为什么整数除以零 1/0 会出错,但浮点数 1/0.0 返回“Inf"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆