cfree 格力高公式求s的值

格里高利公式s/4=1-1/3+1/5-1/7+... 根据这个公式,可以近似计算圆周率л的值。 要求:输入正整数N(N≤40),计算并输出s的值(保留6位小数),其中i取值为[1,N]之内的所有奇数 输入1 输出4.000000 3 2.666667 36 3.086080 37 3.194188

img 自己做的不知道为啥错,求大神指导 并求大神自己解题方法

你写错的原因是你的i本身已经是奇数了,但是你在后面还是2*i-1,这样就相当于只算了1,5,9这样的数,自然就不对了

#include <stdio.h>

int main()
{
    int n;
    float s=0;
    scanf("%d", &n);
    int x=-1;
    for(int i=1;i<=n;i+=2)
    {
        x=-x;
        s+=1.0/i*x;
    }
    s*=4;
    printf("%.6f\n",s);
}