import java.util.Scanner; //编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n public class Test { public static void main(String[] args) { int n = getN(); double sum = 0; if (n % 2 == 0) { for (int i = 2; i <= n; i = i + 2) { sum = sum + 1.0 / i; } } else { for (int i = 1; i <= n; i = i + 2) { sum = sum + 1.0 / i; } } System.out.println(sum); } public static int getN() { int n = 0; Scanner sc = new Scanner(System.in); System.out.println("请输入一个数:"); while (true) { String s = sc.nextLine(); try { n = Integer.parseInt(s); break; } catch (NumberFormatException e) { System.out.println("输入错误,请重新输入:"); } } return n; } }