我正在用c制作Leibniz算法来计算饼图。我不断得到负面结果。是因为我使用了Long Double类型吗?

#include <stdio.h>
#include<math.h>

int main()
{
int iterations;
int counter = 1;
long double nextnum = 1.;
long double answer=0.0;
long double temp = 0.0;

printf("Iterations: ");
scanf("%d",&iterations);

while (counter <= iterations)
{
    if (counter%2 != 1)
    {
        answer = temp + (1/nextnum*4);
        printf("%1Lf\n",answer);
        nextnum = nextnum +2;
        temp = answer;
        counter++;
    }

    if (counter%2 == 1)
    {
        answer = temp - (1/nextnum*4);
        printf("%1Lf\n",answer);
        nextnum = nextnum +2;
        temp = answer;
        counter++;
    }

}

return 0;
}

最佳答案

您在错误的位置乘以4。尝试像original formula中那样计算pi / a

#include <stdio.h>
#include<math.h>

int main()
{
    int iterations;
    int counter = 1;
    long double nextnum = 3.0;
    long double answer = 0.0;
    long double temp = 1.0;

    printf("Iterations: ");
    scanf_s("%d", &iterations);

    while (counter <= iterations)
    {
        if (counter % 2 != 1)
        {
            answer = temp + (1 / nextnum);
            printf("%1Lf\n", answer);

            temp = answer;
        }

        else
        {
            answer = temp - (1 / nextnum);
            printf("%1Lf\n", answer);
            temp = answer;
        }
        nextnum += 2;
        counter++;
    }

    printf("\n Answer: %1Lf\n", 4 * answer);

    return 0;
}

09-17 16:18