我为什么不断得到负值?

问题描述 投票:0回答:1

我正在用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;
}
c loops while-loop double
1个回答
-1
投票

您在错误的位置乘以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;
}
© www.soinside.com 2019 - 2024. All rights reserved.