问题描述
你好,我有一个赋值器,其中我必须创建一个函数,该函数使用taylor级数为给定的x值计算正弦值。我已经编写了以下代码,看来问题发生在析因的部分,但我不确定吗?
#include<math.h>
#include<stdio.h>
double x;
int n;
double fact = 3;
double sum = 0;
double factsum = 1;
int factf(double fact)
{
for (int i = 1; i < fact; i++)
{
factsum = factsum * i;
}
}
double taylor_sine(double x,int n)
{
x = (x*3.14)/180;
for (int i = 0; i < n; i++)
{
sum = sum + (pow(x,fact)/factf(fact));
fact = fact + 2;
factsum = 1;
}
sum = x - sum;
}
int main(void)
{
printf("Enter the value for x\n");
scanf("%lf",&x);
printf("Enter the number of precision\n");
scanf("%d",&n);
taylor_sine(x,n);
printf("Sum = %lf\n",sum);
}
解决方法
您的代码有几个问题,最关键的是:
您的阶乘函数会计算(n-1)的阶乘。
它不返回计算值(return factsum;
)。
您错误地对待交替符号。您必须在每次迭代中更改符号。
正如其他人已经指出的那样,您应该真正使用函数的返回值,而不是写入全局变量。
您将float“ precision”参数用作泰勒项的最大数量。
固定这些值后,计算就可以进行(尽管效率很低且准确性很差)。