0
package homework1C;

public class Homework1C {

public static void main(String[] args){
    double term =2,sum;
    int n;
    final double difference = 0.0000000001;
    double x;
    for(sum=0.0,n=0;term > difference;n++){


        x = find_n_fact(n);
        term=1.0/x;
         sum+=term;
         n++;
    }

        System.out.printf("e : %f\n", sum);
        System.out.printf("term : %d\n", n);

    }

public static int find_n_fact(int n){
int i;
int fact = 2;
for(i = n; i>2;i--){

    fact *= i;
}
    return fact;
}

}

这就是我被要求做的事情:编写另一个 Java 应用程序来查找并显示 e(自然对数)的近似值。使用以下近似公式,从 n 作为 2 开始,以 1 递增,直到 e 的两个连续值相差小于 0.0000000001,并且不仅显示近似值,还显示在最后一个近似值中使用了多少项 n。公式为: e = 1/0 的近似值!+ 1/1!+ 1/2!+ 1/3!+ ... , 其中 n! 是 n 阶乘

这是我目前对该程序的输出

e : 1.043081
term : 20

我究竟做错了什么 ?答案应该是

e: 2.71828
term: 15

如何解决这个问题?

4

3 回答 3

0

In the sum, the term that follows 1/n! is 1/(n+1)!. That means there is no reason to start all over again (computing (n+1)! from scratch), but instead just divide the current term value by the next n value; ie the loop content only needs to be

    term /= n;
    sum += term;

where you initialize n, term and sum to 1 (since 1/0! is 1) before the loop starts. Of course take n++ out of the loop, because the for statement includes an n++ itself. This approach gets rid of your find_n_fact() function and the errors in it. (Minor note: 1e-10 is more convenient to write than 0.0000000001, and has the same value.) One more suggestion: Add a statement like

System.out.printf("sum : %12.10f   term: %12.10f  1/t: %12.10f,  n: %d\n", sum, term, 1/term, n);

inside your loop when debugging; this will make errors like the extra n++ and the error in the factorial function obvious.

于 2012-10-09T06:30:02.983 回答
0

你犯的几个错误:

  • 你的阶乘方法是错误的。尽管可以在您尝试时以迭代方式完成,但我建议您使用递归版本
  • 您在 for 循环中将 n 递增main()两次,这是无稽之谈。

这是适合您的完整工作代码:

public class Homework1C {
    public static void main(String[] args) {
        double term = 2, sum = 0;
        final double difference = 0.0000000001;
        int n;

        for (n = 0; term > difference; n++) {
            term = 1.0 / find_n_fact(n);
            sum += term;
        }

        System.out.printf("e : %f\n", sum);
        System.out.printf("term : %d\n", n);
    }

    public static double find_n_fact(int n) {

        if (n == 0 || n == 1)
            return 1.0;

        return n * find_n_fact(n - 1);
    }
}

阶乘方法的迭代版本在这里:

public static double find_n_fact(int n) {
    double i, fact = 1;

    if(n < 0) // for negative numbers, factorial is nonsense.
        return -1;

    for (i = n; i > 1; i--)
        fact *= i;

    return fact;
}
于 2012-10-09T05:26:46.917 回答
0

当 n 为 0 或 1 时,您的阶乘函数看起来find_n_fact不正确。

于 2012-10-09T05:19:30.057 回答