954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How do you code a series?

I find a problem which says

An approximate value of pi can be calculated using the series given below:
Pi = 4 [ 1 – 1/3 + 1/5 – 1/7 + 1/9 … + ((-1)n)/(2n+1)]
Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation. Includes a loop that allows the user to repeat this calculation for new values n until the user says she or he wants to end the program.

As far as I know, the we can use the formula given in the problem, put it in the loop and using input from the user to determine when it should end. But I can't code it at all [IMG]http://images.devshed.com/fds/smilies/mad.gif[/IMG] I mean... its like a series that keeps on going if not mistaken. How can I code this? Plus, it swtiches from + to - repeatedly. zz confused.

ice_tea_lemon
Newbie Poster
7 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

C version: returns pi/4

#include <stdlib.h>

double pi_over_4(int n)
{
	double iter=3;
	int eveodd=1;
	double pi=0.;

    for(pi=1.; n>0; n--, iter+=2., eveodd=!eveodd)	
	{		
		if(eveodd)
		    pi-=1./iter;
		else				
	                    pi+=1./iter;
	}	
	return pi;
}
jim mcnamara
Junior Poster
180 posts since May 2004
Reputation Points: 62
Solved Threads: 10
 

wow...what would this same code be like in c++? i want to start c++ as a hobby. xd

nekomata
Newbie Poster
2 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You