我的程序首先找到n形式用户输入的阶乘。然后我接受并执行1 / n以在该位置找到该术语。然后,我需要将所有以前的术语加在一起,以找到该系列中该术语的e的近似值。
它在系列中打印出正确的第n个术语,但是当我将它们加在一起时,它们总是出错。
以下是我的程序的代码:
import java.util.*;
public class Lab01b {
public static void main(String[]args){
Scanner scan = new Scanner(System.in); // Creates a Scanner object to get input from the user
double term = -1.0;
double e = 0.0;
/* Loop to recieve user's input */
while(term < 0){
System.out.println("Enter factorial number");
term = scan.nextDouble();
if(term < 0)
System.out.println("Enter a number greater than 0");
}
e = factorial(term);
System.out.println("Term: "+term);
System.out.println("e: "+e);
System.out.println("Final: "+ e(e, term));
}
/*Method to calculate a factorial*/
public static double factorial(double n){
double factorial =1;
for(int i =1; i <= n; i++){
factorial *= i;
}
return factorial;
}
/* Method to calculate e^x*/
public static double e(double n, double input){
double factorial = 0.0;
double counter = 0.0;
for(int i = 0; i < input+1; i++){
factorial = 1/n;
counter += factorial;
}
return counter;
}
}
答案 0 :(得分:3)
这不是一个编程问题,而是一个数学问题 - 你在计算事实错误:
不是1 / n
,而是1 / n!
。所以你的工作是总结事实的条款。我会保存以前的事实,所以你需要做的就是把它除以n。此外,请确保所有除法是 double 除法而不是int除法,因为int / int将返回int。
因此1/20
将返回0,而1.0 / 20
将返回0.05。
如,
fact = 1;
sum = 1.0;
for (int i = 1; i < max; i++) {
fact *= i;
sum += 1.0 * n / fact;
}
答案 1 :(得分:0)
你在计算一个阶乘错误,它是1 * 2 * 3 ... * n,而不是1 + 2 + 3 ... + n!
double factorial = 1.0;
for(int i = 1 ; i <= input ; i++) {
factorial *= i;
}
希望有所帮助:)