Skip to content

Instantly share code, notes, and snippets.

@a0x
Last active October 16, 2015 15:49
Show Gist options
  • Save a0x/ac548f8f72bc5f6ca2dd to your computer and use it in GitHub Desktop.
Save a0x/ac548f8f72bc5f6ca2dd to your computer and use it in GitHub Desktop.
public class TestPI{
public static void main(String[] args){
// args[0] 是运行时输入的参数,也可以预先在程序中设定好数值。
int time = new Integer(args[0]).intValue();
double result = 0;
for(int i = 1; i <= time; i++){
double value = 4.0 / (2.0 * i - 1.0);
if (i % 2 == 1) {
result += value;
}
else {
result -= value;
}
}
System.out.println(result);
}
}
@a0x
Copy link
Author

a0x commented Oct 16, 2015

args[0]是运行该程序时需要从键盘输入的参数,指的是循环运行的次数,即公式中的项数,也可以在程序中指定为固定的数值。

运行方法:

  1. 编译为字节码文件:javac TestPI.javac
  2. 运行Java程序:java TestPI 99999 (最后的数字也可以为其他值)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment