π/2 ≈ 1 + 1/3 + 1/3 * 2/5 + 1/3 * 2/5 * 3/7 + 1/3 * 2/5 * 3/7 * 4/9 + ...
求π的值?
public static void main(String[] args) {
DecimalFormat df = new java.text.DecimalFormat("#.############");
double sum = 1;
int i = 1;
double t;
System.out.printf(sum + "");//控制台输出格式,非必要代码
do{
t = 1;
System.out.printf(" + ");//控制台输出格式,非必要代码
for(int j = 1; j <= i; j++) {
t = t*((j*1.0)/(2*j + 1));
/*控制台输出格式,非必要代码*/
if(j == i) {
System.out.printf(j + "/" + (2 * j + 1));
}else {
System.out.printf(j + "/" + (2 * j + 1) + "*");
}
}
sum += t;
i++;
}while (t >= 1e-12);
System.out.println();//控制台输出格式,非必要代码
System.out.println("π = " + df.format(sum*2 - t));
}