Help computing Pi!
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Help computing Pi!

  1. #1
    Join Date
    Oct 2013
    Posts
    1

    Help computing Pi!

    Hi. We have been asked to compute Pi with the formula:

    PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...
    Allowing the user to determine the amount of computations to perform(5 shown in the above formula)

    I'm completely stumped at this stage and cannot get the correct answer no matter what I try. Does anyone have any idea where a problem is in this code?

    Code:
    import javax.swing.JOptionPane;
    
    import java.util.Scanner;
    
    public class pi 
    {
    
    public static void main(String[] args) 
    	{
    
    	String digitInput = JOptionPane.showInputDialog( "How many terms would you like to be used in the computation?");
    
    	Scanner termScan = new Scanner (digitInput);
    	
    	double terms = termScan.nextDouble();
    
    		
    		double pistart = 3;
    		double termCount = 0;
    		double num1 = 2;
    		double num2 = 3;
    		double num3 = 4;
    		double four = 4;
    
    		while (termCount <= terms)
    		{
    			
    		
    			double piloop = (four/(num1 * num2 * num3));
    			double finalpi = pistart + piloop;
    
    			num1 = num1 + 2;
    
    			num2 = num2 + 2;
    
    			num3 = num3 + 2;
    			
    			four = four * (-1);
    
    			termCount ++;
    			
    			JOptionPane.showMessageDialog(null, + finalpi);
    			
    		}	
    	}
    }

  2. #2
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,424

    Re: Help computing Pi!

    Try printing out the values of each term as they are computed to see if they are correctly computed.

    Move the JOptionPane call outside of the loop
    Norm

  3. #3
    Join Date
    Jun 2011
    Posts
    7

    Re: Help computing Pi!

    Each time you loop you overwrite the double finalpi with the statement
    double finalpi = pistart + piloop;
    pistart needs to be used only the first time. Either move it out of the loop or check if it is the first time the loop executed and then use the pistart.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center