Java中运行表达式return 1.0/0.0会发生什么?return 1/0会发生什么?

在Java中运行表达式:1.0 / 0.0,会有返回么?会不会抛出异常或者是编译器error? 
那1/0呢? 

① 浮点数除法,1.0/0.0不会抛出异常,值为Infinity。

This is another tricky question from Double class. Though Java 
developer knows about the double primitive type and Double class, 
while doing floating point arithmetic, they don’t pay enough attention 
to Double.INFINITY, NaN, and -0.0 and other rules that govern the 
arithmetic calculations involving them. The simple answer to this 
question is that it will not throw ArithmeticExcpetion and return 
Double.INFINITY.

② 整数除以0时会抛出ArithmeticException。

Exception in thread "main" java.lang.ArithmeticException: / by zero

补充:如何判断一个x是否为NaN or Infinity? 
不能使用 return x == NaN,因为无论如何,返回均为false,即使x为NaN; 
必须使用Doubl类的静态方法isNaN(); 
示例:

public class Main1 {

    public static void main(String[] args) {
            double x = Double.NaN;
            System.out.println(x == Double.NaN);
            System.out.println(Double.isNaN(x));
    }
}


输出:

false
true
1
2
对Infinity同理:

public class Main1 {

    public static void main(String[] args) {
            double x = 1.0 / 0.0;
            System.out.println(x == Double.NEGATIVE_INFINITY);
            System.out.println(x == Double.POSITIVE_INFINITY);
            System.out.println(Double.isInfinite(x));
    }
}


输出:

false
true
true
1
2
3
可以看出 1.0/0.0为POSTIVE_INFINITY,说明java里面0.0是+0.0。如果1.0/0.0由于默写原因导致符号反转了,上述代码将等到相反结果。为了避免符号带来的麻烦,提高程序鲁棒性,建议使用Double.isInfinite()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值