用sin(x)≈x-x^3/3!+x^5/5!-……+(-1)^(n-1)*(x^(2n-1))/(2n-1)!的公式求近似值,直到最后一项绝对值小于0.00001为止。设x=7。答案(0.6569827)
求各位大佬解惑!
#include <math.h>
#include <stdio.h>
double fuc(int m); //修改类型,否则x超过2就跑不了,试过没有问题了
int main()
{
double x, term, sum;
int n = 1;
x = 7;
term = x;
sum = x;
do
{
n += 1;
term = pow((float)-1, (float)(n + 1)) *
pow((float)x, (float)(2 * n - 1)) / fuc(2 * n - 1);
sum += term;
} while (fabs(term) >= 1e-5);
printf("%lf\n", sum);
return 0;
}
double fuc(int m)
{
double t, p;
for (t = 1, p = 1; t <= m; t++)
p *= t;
return p;
}
供参考:
#include <stdio.h>
#include <math.h>
int main()
{
int i = 1;
double s, t, x = 7.0;
//scanf("%lf", &x);
s = x; t = x;
while (fabs(t) >= 1e-5)
{
t = -t * x * x / (4 * i * i + 2 * i);
s += t;
i++;
}
printf("sin(x)≈%.7f\n", s);
return 0;
}