gpt4 book ai didi

Java Math.pow((1/(1+1),1) 无法正确计算

转载 作者:行者123 更新时间:2023-12-01 06:38:34 25 4
gpt4 key购买 nike

我尝试用 Java 进行一些实验,然后出现了这个问题:

public class TestRandom {
public static void main(String[] args){
System.out.println(Math.pow((1/(1+1)),1));
}
}

评估为0.0 ,最初很可能是 NaN。

我有什么问题吗?或者有真正的解释吗?

最佳答案

那里有一个整数除法。 1/20,而不是 0.5

您可以尝试将表达式更改为 Math.pow((1.0/(1+1)),1) 以强制其为浮点除法。

编辑

Java 中的除法设计方式与 C 和 C++ 中的设计方式相同,后者出现于 Java 之前。当您使用两个 int 类型的表达式进行除法时,您将得到 int 类型的结果。这是语言设计者做出的选择,无论好坏,我们现在都坚持这个选择。但基本上,这意味着除法的任何小数结果都会向下舍入(严格来说,朝零舍入)。在本例中,1/2 将四舍五入为 0

同样的事情也会发生在 long 上。

Java Language Specification

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

关于Java Math.pow((1/(1+1),1) 无法正确计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879488/

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