我大概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();
}
}
}
外一所学校的项目来计算π作为'double'的;我更喜欢['Math.PI'](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#PI)。 –