【发布时间】: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语句。相反,一个带有else的if语句就足够了。
标签: c loops while-loop double