深表歉意,因为我确信我很愚蠢,但我无法解决这个问题,而且我的学校截止日期即将到来:(
通过重复此过程,这段代码应该近似于数字 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 代表 double )或 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
关于java - 我正在尝试使用 for 循环获取阶乘;但我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68138333/