京东8.6笔试 Java
第一题:
求f(n) = 1/5-1/10+1/15-1/20+...+1/(5(2n-1)) + 1/(5(2n))
结果保留小数点后四位;
import java.util.Scanner;
public class Main01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
System.out.printf("%.4f", compute(n));
}
}
private static double compute(int n) {
if (n <= 0) {
//return (float) (Math.round(0.0f * 10000)) / 10000;
return 0;
}
float res = 0;
for (int i = 1; i <= n; i++) {
res += 1.0000 / (5 * (2 * i - 1) * (2 * i));
}
//return (Math.round(res * 10000)) / 10000;
return res;
}
}
查看6道真题和解析