因此,对于我的计算机编程入门类(class),我们必须编写 3 个单独的函数,一个用于计算阶乘,一个用于计算幂 (x^n),一个用于计算具有给定误差的泰勒级数的项数近似。每次我运行程序时,它都会打印 Nterms=1,而不是 100、300、1000 等。
这可能是我循环中的一个简单错误,但我找不到它。感谢您的帮助!
#include<stdio.h>
#include<math.h>
double power(float A, int B)
{
double sum=1.00;
int nterms=1;
while ( nterms <= B && B > 0)
{
sum = A*sum;
nterms++;
}
return sum;
}
double factorial(int b)
{
double fact=1.00;
while (b >= 2)
{
fact = b*(b-1)*fact;
b = b-2;
}
return fact;
}
int Terms(float X, float a)
{
int N=1,l;
double L,R;
while (L < a && a <= R)
{
l=N+1;
L= (power(X,l)/(factorial(l)));
R= (power(X,N)/(factorial(N)));
N++;
}
return N;
}
int main()
{
float x, delta;
double sum=0.00, term=0.00;
int n, Nterms;
printf("Please enter a decimal number. x=");
scanf("%f",&x);
printf("Please enter an another number. delta=");
scanf("%f",&delta);
Nterms=Terms(x,delta);
printf("Nterms=%d\n",Nterms);
for(n=0;n<Nterms;n++)
{
if( n==0 || n==1 )
{
sum = 1 + x;
}
else
{
sum = sum + term;
term = (power(x,n))/(factorial(n));
}
}
printf("The approximation for e^(%f)=%.4f",x,sum);
return 0;
}
最佳答案
Terms
函数始终返回 1 意味着 N 永远不会改变其初始值,这意味着您永远不会进入 while 循环
while (L < a && a <= R)
这意味着永远不会满足条件。
我建议单步执行,当您需要更多项时,注意您认为 L 和 R 应该是什么,并在您到达那里时检查它们实际是什么而不初始化它们。
关于c - 我为类制作的 e^x 函数得到了错误的输出,并且得到了错误的项数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28616627/