我是新的 C 程序员,我正在做一个学校项目,我必须近似值或 pi。我的教授说我们必须使用 . 声明所有整数项long double
。控制台显示我询问用户给定函数的近似 pi 的项数。我输入 1 作为术语数,但代码返回 -0.00000000 而不是 4.00000000。
#include <stdio.h>
#include <math.h>
long double approx1(int terms)
{
long double pi = 0;
long double num = 4;
long double denom = 1;
int i;
for(i=1; i <= terms; i++)
{
if(i%2 != 0)
{
pi=pi+(num/denom);
}
else
{
pi=pi-(num/denom);
}
denom = denom + 2;
}
printf("%.8Lf\n", pi);
}
int main()
{
int terms;
long double pie;
printf("input number of terms, input 0 to cancel\n");
scanf("%d", &terms);
while(terms != 0)
{
if(terms > 0)
{
pie = approx1(terms);
printf("%.8Lf\n", pie);
printf("GG mate\n");
break;
}
else
{
printf("Incorrect input, please enter a correct input\n");
scanf("%d", &terms);
}
}
}
我在让它工作方面没有任何成功(虽然它适用于浮动)。我究竟做错了什么?(顺便说一句,我正在使用带有编译器的代码块。)