[英]Why doesn't Java calculate this calculation right?
I have recently started learning Java.我最近开始学习Java。 I started working on a simple mathematical project for approximating Euler number with (1 + 1 / x)^x.
我开始研究一个简单的数学项目,用 (1 + 1 / x)^x 逼近欧拉数。 But at the very first step, the program returned the wrong value.
但是在第一步,程序返回了错误的值。 Here is my minimised code, where the solution is wrong.
这是我最小化的代码,解决方案是错误的。
public class MyClass
{
public static void main(String[] args)
{
System.out.println(1 + 1 / 2);
}
}
The program returns 1. The result seems to me pretty contradictory.程序返回 1。结果在我看来很矛盾。 How can 1 + 1 / 2 return 1?
1 + 1 / 2 如何返回 1? I was expecting 1.5.
我期待 1.5。
I tried some debugging:我尝试了一些调试:
double x = 1 + Math.pow(2, -1);
System.out.println(x);
And now it is working.现在它正在工作。 How come that?
怎么会这样?
I was making a division on the two integers.我正在对两个整数进行除法。 I should make this on two doubles or floats:
我应该在两个双打或浮动上做这个:
System.out.println(1.0 + 1.0 / 2.0);
And since we can shorten the doubles 1.0 -> 1., we could shorten this:因为我们可以缩短双打 1.0 -> 1.,我们可以缩短这个:
System.out.println(1.+1./2.);
Thank you for your answer!谢谢您的回答! (Especially Naman , njzk2 and FredK in the comments.)
(特别是评论中的Naman 、 njzk2和FredK 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.