0

QUESTION : Find value of pi using the series : pi = 4 – 4/3 + 4/5 – 4/7 + ... + ((-1)^(n-1)) 4/(2n+1) + ...

And my code is :

#include<stdio.h>
#include<math.h>
int main () {

int n,i;
float pi;

printf("Enter number of terms : \n");
scanf("%d",&n);
pi = 0 ; 
for(i=1 ; i<n ; i++) {

    if (i%2==0)
         pi = pi + (4/(2*i)+1);
    else
         pi = pi - (4/(2*i)+1);



}

printf("value of pi is %f \n",pi);



return 0;
}

The output I'm getting is

value of pi is -1.000000 

(for ANY odd input)

and

value of pi is -2.000000 

(for ANY even input)

I know there might be some other methods to do this one. But I wish to know what's wrong with this one. I think there is a problem in

 if(i%2==0)

Thank you.

Chand Sethi
  • 136
  • 1
  • 1
  • 9

1 Answers1

2
4/(2*i)

This is integer division, change it to:

4.0/(2*i)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294