题目
Description
计算pi/4=1-1/3+1/5-1/7+….+1/n,
Input
n
Output
根据该算式计算的pi的值(精确6位有效数字)
Sample Input
100
10000
1
Sample Output
3.121595
3.141393
4.000000
代码块
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cn = new Scanner(System.in);
while (cn.hasNext()) {
int n = cn.nextInt();
double sum = 0;
for (int i = 1,j = 0; i <= n; i+=2,j++) {
if (j % 2 == 0)
sum += 1.0 / i;
else
sum -= 1.0 / i;
}
System.out.printf("%.6f\n",sum*4);
}
}
}