我尝试用泰勒公式(1 + x + x^2/2 + x^3/6 + ... + x^n/n!)来算exp的近似值和准确值进行比较,k表示循环的次数,a和sum用来表示 n的阶乘,pow(x,n)为了用来表示x的n次方,但是为什么运行出来问题很大啊,问题应该就在数据类型的选择或者循环内,麻烦各位帮忙看看哪里的问题啊
int main()
{
int k,a;
float i,j,sum=1;
double x,n;
printf("Enter the value of x:");
scanf("%f",&x);
j=1;
n=0;
i=1;
printf("Enter the number of the loops:");
scanf("%d",&k);
while(n<k) /*Exit loop condition*/
{
n++;
for(a=1;a<=n;a++)
{
sum=sum*i;
}
i=pow(x,n)/sum;
j+=i;
}
printf("exp(x)=%f\n",exp(x));
printf("from the formula that e to the x power j is:%f\n",j);
return 0;
}
我尝试用泰勒公式(1 + x + x^2/2 + x^3/6 + ... + x^n/n!)来算exp的近似值和准确值进行比较,k表示循环的次数,a和sum用来表示 n的阶乘,pow(x,n)为了用来表示x的n次方,但是为什么运行出来问题很大啊,问题应该就在数据类型的选择或者循环内,麻烦各位帮忙看看哪里的问题啊
#include <stdio.h>
#include <math.h>
int main() {
int k, a;
float x;
float current_term; // 当前项的值
float sum = 1; // n 的阶乘
float i = 1; // x 的 n 次方
float j = 0; // 公式的值
float n = 0; // 循环次数
// 读入 x 和循环次数 k
printf("Enter the value of x:");
scanf("%f", &x);
printf("Enter the number of the loops:");
scanf("%d", &k);
// 计算公式中的每一项
while (n < k) {
// 计算当前项的值
current_term = i / sum;
// 更新 j
j += current_term;
// 更新 i 和 sum
i *= x;
sum *= (++n);
}
// 输出 exp(x) 和用公式计算的结果
printf("exp(x) = %f\n", exp(x));
printf("from the formula that e to the x power j is: %f\n", j);
return 0;
}