C语言 泰勒公式计算sin(x)
利用泰勒级数计算sin(x) 的值,直到最后一项的绝对值小于10-5,并统计共累加了多少项。
输入x的值,输出sin(x)的值(小数点后保留3位)和此时累加了多少项。
输入样例:
3
输出样例 :
0.141
9
#include <stdio.h>
#include <math.h>
double fact(int n)
{
if (n == 0)
return 1;
return fact(n - 1)*n;
}
int main()
{
double x, sum = 0, term = 1;
int n = 1, t = 1;
scanf("%lf", &x);
while (term >= 1e-5) {
term = pow(x, 2 * n - 1) / fact(2 * n - 1);
sum += t * term;
t = -t;
n++;
}
printf("%.3lf\n%d", sum, n - 1);
return 0;
}