(Java) 为什么我的代码没有打印出完整的数字?

huangapple go评论100阅读模式
英文:

(Java) Why is my code not printing out the full number?

问题

我正在尝试使用以下Java代码计算e的值:

  1. import java.util.Scanner;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Scanner scnr = new Scanner(System.in);
  5. int n;
  6. System.out.print("值的数量:");
  7. n = scnr.nextInt();
  8. double e = 0.0;
  9. double f = 1.0;
  10. for (int i = 1; i <= n; i++) {
  11. f = f * (i);
  12. e += 1 / f;
  13. }
  14. e += 1;
  15. System.out.print(e);
  16. }
  17. }

然而,当我打印出e时,它的数字被限制为2.7182818284590455,而不是一个更具体的数字(类似于2.7182818284590455 x 10^-308)。这是我使用的类型有问题吗?

英文:

I'm trying to calculate the value of e using the following Java code:

  1. import java.util.Scanner;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Scanner scnr = new Scanner(System.in);
  5. int n;
  6. System.out.print(&quot;number of values: &quot;);
  7. n = scnr.nextInt();
  8. double e = 0.0;
  9. double f = 1.0;
  10. for (int i = 1; i &lt;= n; i++) {
  11. f = f * (i);
  12. e += 1 / f;
  13. }
  14. e += 1;
  15. System.out.print(e);
  16. }
  17. }

However, when I print out e, the number it limited to 2.7182818284590455 instead of a much more specific number (2.7182818284590455 x 10^-308 or something similar). Is it a problem with the Types I'm using?

答案1

得分: 1

这个答案

双精度浮点数的小数位数为16

我无法理解你是如何期望得到 2.7182818284590455 x 10^-308 的:

  1. 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...000027182818284590455

这是一个非常小的分数!

根据你的代码,你正在将一个逐渐更小的分数加到 e 上。根据你的代码,你只能期望结果在 2.03.0 之间。

你可能原本想要的是超过16位小数精度。但由于精度限制,使用double无法实现这一点。

英文:

From this answer:
> The number of decimal places in a double is 16.


I can't see how you expect to get 2.7182818284590455 x 10^-308:

  1. 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000027182818284590455

That's a very small fraction!

What you're doing is adding an increasingly smaller fraction to e. Based on your code, you can only expect the result to be between 2.0 and 3.0.


What you probably were looking for was a precision of more than 16 decimal places. That simply can't be achieved using double due to precision limitations.

huangapple
  • 本文由 发表于 2020年10月15日 05:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64361589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定