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

标签 java

我尝试用 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/

相关文章:

java - fragment 中缺少 TextView 数据(文本)

java - 为什么这需要这么长时间才能运行?

java - 将图像、音频和视频保存到 SD 卡

java - 如何从 JFace 对话框访问工作台状态行管理器

java - com.mchange.v2.resourcepool.basicresourcepool$acquiretask 获取尝试失败端口号无效

java - 如果然后条件在 java 中使用正则表达式

java - Android应用程序搜索下载文件夹中的特定文件

java - 在 Java 中读取文件并计算相同条目的数量

java - Spring AOP : Getting return types in after-returning method

java - 实现在 Servlet 中在 XML 和 JSON 之间切换的 REST api