简体   繁体   English

用于计算正弦的C程序给出了不准确的结果

[英]C program to calculate sine is giving an inaccurate results

I have to write this program only with #include<stdio.h> . 我只能用#include<stdio.h>编写这个程序。

I have to read the highest power of the series 'n' from the user. 我必须从用户那里读到'n'系列的最高功率。

When x=45 and n=9 , then the program gives me 0.7068251967 . x=45 and n=9 ,程序给出0.7068251967 But when I use my calculator for the same then I get 0.7068251828 . 但是当我使用我的计算器时,我得到0.7068251828

I also have to use recursion. 我还必须使用递归。

#include<stdio.h>

float pow(float n, int p)
{
if(p == 0)
    return 1;
else
    return n * pow(n, p-1);
}

int fact(int n)
{
if(n == 0)
    return 1;
else
    return n * fact(n-1);
}

int main()
{
int n, x, i, sign = 1;
float sum, r;


printf("Enter the angle in degrees.\n");
scanf("%d", &x);

r = 3.14 * x / 180.0;

printf("Enter the odd number till which you want the series.\n");
scanf("%d", &n);

if(n % 2 == 0)
    printf("The number needs to be an odd number.\n");
else
{


for(i = 1, sum = 0; i <= n; i += 2, sign *= -1)
{
    sum += (sign * pow(r, i)) /  fact(i);
}

printf("The sum of the series is %.10f.\n", sum);
}


return 0;
}

I think one cause is the fact that you approximate pi by 3.14. 我认为一个原因是你将pi估计为3.14。 Maybe your calculator takes into consideration more digits of pi. 也许你的计算器会考虑pi的更多数字。 Try using more digits for approximatig pi. 尝试使用更多数字进行近似pi。

@Mat is right, use M_PI instead of your 'poor man' 3.14. @Mat是对的,使用M_PI而不是你的'穷人'3.14。 Besides do not always exponentiate x to the power n or factorials. 此外,并不总是将x取幂为幂n或阶乘。 Notice that the next term of the sum: a_{k+2}=-a_{k}x^2/(k(k-1)), (the even terms are zero) Use something like 请注意,和的下一项:a_ {k + 2} = - a_ {k} x ^ 2 /(k(k-1)),(偶数项为零)使用类似的东西

double s=x,a=x,x2=-x*x;
int i;
for (i=3;i<=n;i+=2)
{
   a*=x2/i/(i-1);
   s+=a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM