所以我正在用数值方法计算e(图片中的第三行)。
我正在增加每次迭代使用的元素数量。当我执行程序时,浮点变量以我不了解的方式运行。这是程序和结果。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int factorial = 1;
int counter = 0;
int iterationNumber;
double total = 0;
int tempCounter;
System.out.print("Enter iteration number: ");
iterationNumber = input.nextInt();
while (counter <= iterationNumber) {
tempCounter = counter;
while ((tempCounter - 1) > 0) {
factorial *= tempCounter;
tempCounter--;
}
total += ((double)1 / factorial);
System.out.println(total);
factorial = 1;
counter ++;
}
}
}
所以我的问题是,为什么e的值在一段时间后开始下降而不是增加?我想学习浮点变量在此程序中的行为及其背后的逻辑。
另一个问题是为什么它开始说无穷大?
最佳答案
n!
快速超过Integer.MAX_VALUE
并溢出到负数。然后,您要在总数中增加一个负数---从而减少总数。
您可以使用BigDecimal
进行计算。它速度较慢,但可以完成工作。