用无穷级数计算pi

时间:2016-03-28 01:44:09

标签: java loops

我用这个系列来近似pi:

pi = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...

我的代码在循环中。当我第一次进入循环时,结果正是我想要的,但第二次却没有。

package pi_number;
import java.util.Scanner;
public class Pi_number {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
{
    Scanner input= new Scanner(System.in);
    double pi=0.0;
    double termx=0.0;

    System.out.print("Enter any key to start or E stop: ");
    String Exit=input.next();


while (!Exit.equals("E"))
  {   
     System.out.print("How many term do you want : ");
     int term=input.nextInt();

     for(int i=1;i<=term; i++)
      {
         if(i%2==0)
           {
              termx=(double)-4/(2*i-1);
           }
           else
              {
                termx=(double)4/(2*i-1);
              }
           pi+= termx;

      }
    System.out.println("Pi number equals="+pi); 

    System.out.print("Enter any key to start or E stop: ");
    Exit=input.next();
  }
 } 
}

2 个答案:

答案 0 :(得分:4)

您需要在计算循环之前初始化termxpi

while (!Exit.equals("E"))
  {   
     termx = 0.0; //initial
     pi = 0.0; //initial
     System.out.print("How many term do you want : ");
     int term=input.nextInt();

     for(int i=1;i<=term; i++)
      {
         if(i%2==0)
           {
              termx=(double)-4/(2*i-1);
           }
           else
              {
                termx=(double)4/(2*i-1);
              }
           pi+= termx;

      }
    System.out.println("Pi number equals="+pi); 

    System.out.print("Enter any key to start or E stop: ");
    Exit=input.next();
  }

答案 1 :(得分:3)

在开始计算你的pi之前初始化你的pi和条件。

试试这段代码:

package pi_number;

import java.util.Scanner;

public class Pi_number {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        double pi,termx;

        System.out.print("Enter any key to start or E stop: ");
        String Exit = input.next();

        while (!Exit.equals("E")) {
            System.out.print("How many term do you want : ");
            int term = input.nextInt();

            pi=0.0;
            termx=0.0;

            for (int i = 1; i <= term; i++) {
                if (i % 2 == 0) {
                    termx = (double) -4 / (2 * i - 1);
                } else {
                    termx = (double) 4 / (2 * i - 1);
                }
                pi += termx;

            }
            System.out.println("Pi number equals=" + pi);

            System.out.print("Enter any key to start or E stop: ");
            Exit = input.next();
        }
    }
}