gpt4 book ai didi

java - 算术异常 :/by zero only works on integers in Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:30 25 4
gpt4 key购买 nike

为什么将数字除以零会有如此不同的答案:

我的代码:

class Test {
public static void main(String[] args){

int a = (int)(3/0.0F);
System.out.println(a);

System.out.println(3/0.0F);

System.out.println(3/0);
}
}

输出:

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

每次我将一个数字除以一个整数(byte、short、int、long)时,它都会抛出 ArithmeticException,而用实数(float、double)时则不会出现这种情况。为什么?

最佳答案

来自 JLS §15.17.2 :

  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

除了:

if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

关于java - 算术异常 :/by zero only works on integers in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com