首页 > 编程 > Java > 正文

第五届蓝桥杯JavaA组第二题

2019-11-08 19:56:18
字体:
来源:转载
供稿:网友

历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式:

pai = 4*(1-1/3+1/5-1/7 ….)

参见【图1.png】

这个公式简单而优美,但美中不足,它收敛的太慢了。 如果我们四舍五入保留它的两位小数,那么:

累积1项是:4.00 累积2项是:2.67 累积3项是:3.47 。。。

请你写出它累积100项是多少(四舍五入到小数后两位)。

import java.text.DecimalFormat;

public class BB0502 {

public static void main(String[] args) { // TODO Auto-generated method stub float a = 1; float sum = 0; for (int i = 1; i <= 100; i++) { float temp = 4/a; if (i%2!=0) { sum = sum + temp; a = a + 2; }else { sum = sum - temp; a = a + 2; } } System.out.PRintln(formatDouble4(sum)); } public static String formatDouble4(double d) { DecimalFormat df = new DecimalFormat("#.00"); return df.format(d); }

}

心得: 1) 四舍五入指定小数位 DecimalFormat df = new DecimalFormat(“#.00”); Return df.format(d)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表