Pi approximation.

The value of pi can be approximated using a series.
pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + 1/(2n-1) - 1/(2n+1))
Write a program to let the user input n number of terms to approximate pi value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
	double pi,x;
	int n;
	cout<<"Enter n terms: ";
	cin>>n;
	for (int i=1;i<=n;i++)
	{ x = (1/(2*i-1)) - (1/(2*i+1)); 
	pi=4*x;
	cout<<"pi = "<<pi<<endl;
	}
	return 0; 
}


The program displays 4 and bunch of 0. Any help?
Last edited on
You're doing integer division.
Replace
x = (1/(2*i-1)) - (1/(2*i+1));
with
x = (1.0/(2*i-1)) - (1.0/(2*i+1));
and see if that fixes it.
it does not....i think my code is wrong... It's just supposed to give you a single value, close to pi
Topic archived. No new replies allowed.