How do you code a series?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Mar 2007
Posts: 7
Reputation: ice_tea_lemon is an unknown quantity at this point 
Solved Threads: 0
ice_tea_lemon ice_tea_lemon is offline Offline
Newbie Poster

How do you code a series?

 
0
  #1
Mar 15th, 2007
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 http://images.devshed.com/fds/smilies/mad.gif 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.
Reply With Quote Quick reply to this message  
Join Date: May 2004
Posts: 178
Reputation: jim mcnamara is on a distinguished road 
Solved Threads: 10
jim mcnamara jim mcnamara is offline Offline
Junior Poster

Re: How do you code a series?

 
0
  #2
Mar 16th, 2007
C version: returns pi/4
  1. #include <stdlib.h>
  2.  
  3. double pi_over_4(int n)
  4. {
  5. double iter=3;
  6. int eveodd=1;
  7. double pi=0.;
  8.  
  9. for(pi=1.; n>0; n--, iter+=2., eveodd=!eveodd)
  10. {
  11. if(eveodd)
  12. pi-=1./iter;
  13. else
  14. pi+=1./iter;
  15. }
  16. return pi;
  17. }
Last edited by jim mcnamara; Mar 16th, 2007 at 3:37 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 2
Reputation: nekomata is an unknown quantity at this point 
Solved Threads: 0
nekomata nekomata is offline Offline
Newbie Poster
 
-1
  #3
33 Days Ago
wow...what would this same code be like in c++? i want to start c++ as a hobby. xd
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC