Math.pow使用小数指数

问题描述 投票:0回答:2

这是我写过的第一个代码。这是我的代码的一部分,用于在用户给出卷的值之后计算立方体和四面体的边长,但输出不正确。我很确定我的方程是正确的,也许我正在使用Math.pow方法错误?

System.out.println("Now, please enter a volume for side or diameter calculation, then press ENTER: ");

volume = input.nextDouble();
cubeSide = Math.pow(volume, (1/3));
sphereDiameter = Math.pow(volume / PI * 6, (1/3));
tetSide = SQRT_2 * Math.pow(3 * volume, (1/3));

System.out.println("");
System.out.println("The Side of your CUBE is : " + cubeSide);
System.out.println("");
System.out.println("The Diameter of your SPHERE is : " + sphereDiameter);
System.out.println("");
System.out.println("The Side of your TETRAHEDRON is : " + tetSide);

关于如何获得正确输出的任何想法?

java floating-point exponentiation
2个回答
1
投票

你的问题是这个Division of integers in Java的一个例子

在Bassically中,你需要将Math.pow()的1/3部分强制转换为double,因为如果你没有默认使用它,它将把结果作为整数(总是0)。

例如:

    double volume = 15.34;
    double fraction = (double) 1/3;
    double cubeSide = Math.pow(volume,fraction);
    System.out.println(cubeSide);

输出是

2.4847066359757295

否则输出始终为1.0。这是任何数字上升到零的结果。

如您的评论中所述,当输入为:

1000

输出应该是一个整体:

10

但实际上是:

9.999999999999998

最简单的解决方案可能只是:

float roundedValue = Math.round(cubeSide);

并说:那不是我的问题。但我们想了解这是怎么回事。就像这个世界上的大多数事情一样,你不是第一个面对这个问题的人。让我们做一些研究,发现在StackOverFlow中有人问过:

在第一个链接中,建议阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic

我不会重复那些比我更了解的聪明人所说的话,所以我强烈建议你阅读上面的链接。


3
投票

1/30 - 当被除数和除数都是积分时,/执行积分除法。你想要1.0 / 31 / 3.01.0 / 3.0,评估为0.3333333-ish。

© www.soinside.com 2019 - 2024. All rights reserved.