*题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n(利用指针函数)
public class 第三十九题按条件计算数列的函数 { public static void main(String[] args) { System.out.print("请输入一个整数"); Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n < 0 || n > 100000) { System.out.println("输入的范围错误"); } else { System.out.println("数列的和为:"+getSequenceSum(n)); } } // 获取数列的和
public static double getSequenceSum(int n) { double result = 0; //计算偶数数列的和
if(n % 2==0 ) { for(int i = 2; i < n+2; i+=2) { result += 1.0/i; } return result; } else { //计算奇数数列的和
for(int j = 1; j < n+2; j+=2) { result += 1.0/j; } return result; } } }