Reputation: 21
I'm trying to code a formula where the user inputs a number n
to calculate Pi
using Pi= n^2/(n-1)(n+1). But for some reason the output is wrong. I don't know if my math is wrong or there's something wrong with the function.
Here is the code :
#include <stdio.h>
#include <math.h>
double pi_array (int n)
{
int i;
double a;
if (n%2==0)
{
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
}
return a;
}
double pi_value (int n)
{
int i;
double pi;
for (i=0;i<=n;i++)
{
pi=pi_array(n);
}
return pi;
}
void main()
{
int n;
scanf("%d",&n);
printf ("%lf\n", pi_value(n));
}
Upvotes: 0
Views: 782
Reputation: 977
Just like @Mat pointed out, in this part of your code:
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
It is doing the same computation again and again because n
does not change its value. The answer pow(n,2)/((n-1)*(n+1))
remains the same even for all the iterations.
Also, on a side note, what formula are you using to calculate your answer? If you put n = 4
, you get the value as 16/15 which equals 1.0667. For n = 5
, the asnwer is 1.041667. They are clearly not equal to pi
. I think thew formula might be wrong itself. You could post the question about the formula on MathStackExchange to get an idea of what the exact formula is, and then implement it in C later :).
Best.
Upvotes: 1