java – 为什么最后一个数字错误?

前端之家收集整理的这篇文章主要介绍了java – 为什么最后一个数字错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么输出最后一个数字错误代码
  1. public class Test {
  2. public static void main(String[] args) {
  3. System.out.println("Hello world");
  4. System.out.println("I wounder is the sqaure root of (2*3) the
  5. same as the sqaure root of 2 and 3 multiplied.");
  6. double squareroot0 = Math.pow(3*2,0.5);
  7. double squarroot1 = (Math.pow(3,0.5) * Math.pow(2,0.5));
  8. System.out.println("So is it the same?");
  9.  
  10. System.out.println("is " + squareroot0 + " the equvielant of " +
  11. squarroot1 + "?");
  12. if(squareroot0 == squarroot1) {
  13. System.out.println("Yes number one and number two are
  14. the same,Congrats!");
  15. }else {
  16. System.out.println("No they are not! ");
  17. }
  18.  
  19. System.out.println(squareroot0);
  20. System.out.println(squarroot1);
  21.  
  22.  
  23. }
  24. }

输出

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

在数学上他们是等同的,那怎么回事?

Math.sqrt()和Math.pow(,0.5)也是一样准确.

解决方法

在有限的计算机中,您无法用无限精度代表数字,所以你需要轮回.你看到的是舍入的效果.这是浮点数的所有使用所固有的.

强制性链接What Every Computer Scientist Should Know About Floating-Point Arithmetic

猜你在找的Java相关文章