问题描述
深表歉意,因为我确定我是个笨蛋,但我没能破解这个问题,而且我的学校截止日期快到了:(
这段代码应该通过重复这个过程来逼近数字e:
e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ...
用户应该使用 int e_stop 指定迭代次数,以便输出如下所示:1 -> 2 2 -> 2.5 3 -> 2.666.. 4 -> 2.708333..
等等,但截至目前,输出如下所示:1 -> 2 2 -> 2 3 -> 2 4 -> 2
import java.util.Scanner;
Scanner Case3Scanner = new Scanner(System. in );
System.out.println("Nivel de exactitud? (iteraciones)?");
//e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ..
int e_stop = Case3Scanner.nextInt();
System.out.println("--------------");
double e_total = 1; //this is the result we will output
double e_divisor = 1; //this is the number we will get the factorial of of
long e_fact = 1; //this is the factorial of e_divisor
for (int e = 1; e <= e_stop; e++) {
//this for-loop should repeat r_stop times.
//this next for-loop should make e_fact equal the factorial of e_divisor
for (int ef = 2; ef <= e_divisor; ef++) {
e_fact *= ef;
}
e_total += 1 / e_fact;
System.out.println(e_total);
e_divisor += 1;
}
解决方法
您的代码中有 2 个错误。
一个是整数除法:
e_total += 1/e_fact
这一行进行整数除法,这意味着您得到一个截断的整数结果(例如,在 Java 中除以 5/2 的结果为 2)。
要表明您不想进行整数除法,您需要执行类似的操作
e_total += 1D / e_fact
(D 代表双)或 e_total += 1.0 / e_fact
您也错误地计算了阶乘。
e_fact
已经有了前一次迭代的结果,所以你不需要在循环中乘以它。
//e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ..
int e_stop = 4;
System.out.println("--------------");
double e_total = 1; //this is the result we will output
long e_fact = 1; //this is the factorial of e_divisor
for (int e = 1; e <= e_stop; e++) {
e_fact *= e;
e_total += 1.0 / e_fact;
System.out.printf("e: %d,e_fact: %d,e_total: %f\n",e,e_fact,e_total);
}
输出:
e: 1,e_fact: 1,e_total: 2.000000
e: 2,e_fact: 2,e_total: 2.500000
e: 3,e_fact: 6,e_total: 2.666667
e: 4,e_fact: 24,e_total: 2.708333