简体   繁体   English

为什么通过添加无限级数的前 N 项来计算 sin(x) 总是返回 0.00000?

[英]Why does calculating sin(x) by adding the first N terms of an infinite series always return 0.00000?

In the following code I try to calculate sin(x) by adding the first N terms of the infinite series.在下面的代码中,我尝试通过添加无限级数的前N项来计算sin(x)


#include <stdlib.h>
#include <math.h>
#define pi 3.14

int main()
{
    float sign=-1,d,x,n,k,factorial=1,y;

    printf("Enter the degree ");
    scanf("%f", &d);

    printf("Enter num of terms ");
    scanf("%f", &n);

    x = d * pi / 180 ;

    for(int i=0,j=1 ; (i==n) && (j<=y) ; i++,j++){
        y = 2*i + 1 ;
        factorial *= j ;
        sign =  - 1 * sign ;
        k +=  sign * pow(x,y) / factorial ;
    }
    printf("%f",k);
}

The problem is that the output is always 0.00000 .问题是 output 总是0.00000

Q : Why does calculating sin(x) by adding the first N terms of an infinge series always return 0.00000?:为什么通过添加无穷级数的前 N 项来计算 sin(x) 总是返回 0.00000?

Summary概括

The (i==n) && (j<=y) line is always false, so the loop never runs. (i==n) && (j<=y)行始终为假,因此循环永远不会运行。

Fixed-up code固定代码

#include <stdio.h>
#include <math.h>
#define pi 3.1415926536

int main()
{
    float d, x, estimate=0.0, factorial=1.0, sign=1.0;
    int i, n;

    printf("Enter the degree ");
    scanf("%f", &d);

    printf("Enter num of terms ");
    scanf("%d", &n);

    x = d * pi / 180;
    for (i=1 ; i<=2*n ; i+=2) {
        estimate += sign * pow(x, i) / factorial;
        factorial *= (i+1) * (i+2);
        sign = -sign;
        printf("%f\n", estimate);
    }
    return 0;
}

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

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