gpt4 book ai didi

java - 为什么最后一个数字不对?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:22 27 4
gpt4 key购买 nike

为什么这段代码的输出只有最后一个数字是错误的:

public class Test {
public static void main(String[] args) {
System.out.println("Hello world");
System.out.println("I wounder is the sqaure root of (2*3) the
same as the sqaure root of 2 and 3 multiplied.");
double squareroot0 = Math.pow(3*2, 0.5);
double squarroot1 = (Math.pow(3, 0.5) * Math.pow(2, 0.5));
System.out.println("So is it the same?");

System.out.println("is " + squareroot0 + " the equvielant of " +
squarroot1 + "?");
if(squareroot0 == squarroot1) {
System.out.println("Yes number one and number two are
the same, Congrats!");
}else {
System.out.println("No they are not! ");
}

System.out.println(squareroot0);
System.out.println(squarroot1);


}
}

输出:

Hello world
I wonder is the sqaure root of (2*3) the same as the sqaure
root of 2 and 3 multiplied.
So is it the same?
is 2.449489742783178 the equvielant of 2.4494897427831783?
No they are not!
2.449489742783178
2.4494897427831783

在数学上它们是等价的,那么这是怎么回事呢?

Math.sqrt()Math.pow(,0.5) 一样准确。

最佳答案

您无法在有限的计算机中以无限精度表示数字,因此您需要四舍五入。你看到的是四舍五入的效果。这是所有 float 使用所固有的。

必填链接:What Every Computer Scientist Should Know About Floating-Point Arithmetic

关于java - 为什么最后一个数字不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6293820/

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