共回答了24个问题采纳率:79.2%
import java.text.DecimalFormat;
import java.util.Scanner;
publicclass Test{
public static void main(String args[]){
x09System.out.print("请输入一个整数: ");
x09Scanner scanner = new Scanner(System.in);
x09int n = scanner.nextInt();
x09double result = 0;
x09for (int i = 1; i <= n; i++){
x09x09// 判断i的奇偶,如果是偶数项则结果为负数
x09x09if (i%2 == 1) {
x09x09x09result += 1.0 / (2*i-1);
x09x09} else {
x09x09x09result += -1.0/ (2*i-1);
x09x09}
x09}
x09
x09// 设置输出格式为小数点后三位
x09DecimalFormat df = new DecimalFormat("0.000");
x09System.out.println(df.format(result));
}
}
1年前
2