我在Java课程中,并且还在班上。任务是: e^x
近似
值ex
可以通过以下总和近似: 1 + x + x^2/2! + x^3/3! + …+ x^n/n!
表达式n!
称为n
的阶乘,定义为:n! = 1*2*3* …*n
。
编写一个程序,该程序将x
值作为输入,并使用n
的四个不同值:5
,10
,50
和100
输出四个ex
的近似值。输出x
用户输入的值,以及所有四个近似值的集合到屏幕上。
样品公式使用:使用 n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
我有所有的工作要工作,包括将n
为5
,10
,50
和100
。我以为我已经弄清楚了阶乘公式,并且我使用了数字4,就像我们显示的样本一样,我的数字匹配了。真的可以使用另一个眼睛。
这是我使用forumla的代码(x
是用户输入的值,n
是5
,10
,50
和100
(:
/**
* 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));