I am new C programmer and I am working on a school project where I have to approximate the value or pi. My professor stated that we have to declare all integer terms using long double
. The console shows me asking the user for the number of terms to approximate pi given a function. I enter 1 for the number of terms however the code returns -0.00000000 instead of 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);
}
}
}
I haven't had any success in getting it to work( it works with float though). What am I doing wrong? (I am using Code Blocks with the included compiler btw.)