[英](Java) Why is my code not printing out the full number?
I'm trying to calculate the value of e using the following Java code:我正在尝试使用以下 Java 代码计算 e 的值:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int n;
System.out.print("number of values: ");
n = scnr.nextInt();
double e = 0.0;
double f = 1.0;
for (int i = 1; i <= n; i++) {
f = f * (i);
e += 1 / f;
}
e += 1;
System.out.print(e);
}
}
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).但是,当我打印出 e 时,它限制为 2.7182818284590455 而不是更具体的数字(2.7182818284590455 x 10^-308 或类似的数字)。 Is it a problem with the Types I'm using?
我使用的类型有问题吗?
From this answer :从这个答案:
The number of decimal places in a double is 16 .
double 中的小数位数是16 。
I can't see how you expect to get 2.7182818284590455 x 10^-308
:我看不出你期望如何获得
2.7182818284590455 x 10^-308
:
0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000027182818284590455
That's a very small fraction!那是很小的一部分!
What you're doing is adding an increasingly smaller fraction to e
.您正在做的是向
e
添加越来越小的分数。 Based on your code, you can only expect the result to be between 2.0
and 3.0
.根据您的代码,您只能期望结果介于
2.0
和3.0
之间。
What you probably were looking for was a precision of more than 16 decimal places.您可能正在寻找超过 16 位小数的精度。 That simply can't be achieved using
double
due to precision limitations.由于精度限制,使用
double
根本无法实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.