需求:编写一个函数,输入n为偶数时,调用方法求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
package com.Summer_0511.cn; import java.util.Scanner; public class Test03 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个数字"); double num = sc.nextDouble(); double sum = 0; if (num%2==0) { for (int i = 2; i <=num; i=i+2) { sum = sum+(1.0/i);//因为i为整数 } System.out.println("输入的偶数运算和为"+sum); } else { for (int i = 1; i <=num; i=i+2) { sum = sum+(1.0/i); } System.out.println("输入的奇数运算和为"+sum); } } }
编写一个函数,输入n为偶数时,调用方法求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
原文:https://www.cnblogs.com/summerdata/p/10849765.html