2016-03-28 132 views
1

我大概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(); 
    } 
} 
} 
+1

外一所学校的项目来计算π作为'double'的;我更喜欢['Math.PI'](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#PI)。 –

回答

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(); 
    } 
+0

谢谢你完美的工作 – vincephng

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(); 
     } 
    } 
}