【问题标题】:Why do i keep getting negative values?为什么我总是得到负值?
【发布时间】:2019-10-06 11:50:38
【问题描述】:

我正在用 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;
}

【问题讨论】:

  • 你从 1 开始 counter,当 counter 是奇数时,你减去一个术语。因此,您正在评估系列 −4 + 4/3 −4/5 + 4/7... 要评估 +4 − 4/3 + 4/5 − 4/7,从 0 开始 counter 或将您的测试换成 @ 987654325@.
  • 顺便说一下,我们一般不会为if (counter % 2 != 1)if (counter % 2 == 1) 等互斥条件编写单独的if 语句。相反,一个带有elseif 语句就足够了。

标签: c loops while-loop double


【解决方案1】:

你在错误的地方乘以 4。尝试计算 pi/a,如 original formula

#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;
}

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多