java – 为什么最后一个数字错误?
发布时间:2020-12-14 05:23:52 所属栏目:Java 来源:网络整理
导读:为什么输出最后一个数字错误代码: 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.")
为什么输出最后一个数字错误代码:
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)也是一样准确. 解决方法
在有限的计算机中,您无法用无限精度代表数字,所以你需要轮回.你看到的是舍入的效果.这是浮点数的所有使用所固有的.
强制性链接:What Every Computer Scientist Should Know About Floating-Point Arithmetic (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读