试图计算一个阶乘e^x,x是用户进入的内容,在公式上遇到麻烦

  • 本文关键字:麻烦 遇到 用户 一个 阶乘 计算 java
  • 更新时间 :
  • 英文 :


我在Java课程中,并且还在班上。任务是: e^x近似

ex可以通过以下总和近似: 1 + x + x^2/2! + x^3/3! + …+ x^n/n!表达式n!称为n的阶乘,定义为:n! = 1*2*3* …*n

编写一个程序,该程序将x值作为输入,并使用n的四个不同值:51050100输出四个ex的近似值。输出x用户输入的值,以及所有四个近似值的集合到屏幕上。

样品公式使用:使用 n = 5 1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!

使用近似值计算E^7

我有所有的工作要工作,包括将n51050100。我以为我已经弄清楚了阶乘公式,并且我使用了数字4,就像我们显示的样本一样,我的数字匹配了。真的可以使用另一个眼睛。

这是我使用forumla的代码(x是用户输入的值,n51050100(:

    /**
     * myFact takes in x and calculates the factorial
     * @param x
     * @param n
     * @return the factorial as a long
     */
    public static long myFact(int x, int n) {
        //declare variables
        long sum = x;
        for (int i=2; i <= n; i++) {
             sum += ((Math.pow(x, i))/i);
        }
        return (sum + 1);
    }
}

这是我调用该功能的主要类。我想的错误也可能存在:

public static void main(String[] args) {
    //declare variable for user input and call method to initialize it
    int x = getNumber();
    long fact;
    int n;
    //Output first line
    System.out.println("Nt approximate e^" + x);
    for (n = 5; n <= 100; n *= 2) {
        if (n == 10) {
            fact = myFact(x, n);
            System.out.println(n + "t " + fact);
            n += 15;
       } else {
            fact = myFact(x, n);
            System.out.println(n + "t " + fact);
        }
    }
}

感谢您看看这一点,我花了几个小时才能得到这一点,因为老师给了我们很少的帮助。

您在

中犯了一个错误
sum += ((Math.pow(x, i))/i);

在这里您需要计算 i!。在您的代码中添加以下方法

public static int fact(int i){
    int fact = 1;
    for (int n = i; n > 0; n--) {
        fact = fact * n;
    }   
    return fact;
}

还将sum =((Math.pow(x,i((/i(更改为

sum += ((Math.pow(x, i))/fact(i)); 

最新更新