【程序39】
题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+…+1/n,当输入n为奇数时,调用函数1/1+1/3+…+1/n(利用指针函数)
import java.util.Scanner;
public class B_39 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个数:");
int number = sc. nextInt();
if(number%2 == 0){//偶
double number1 = ou(number);
System.out.print(number1);
}else{//奇
double number1 = ji(number);
System.out.print(number1);
}
}
public static double ou(int n){
int i = 2;
double count=0.0;
while(i<=n){
count += 1.0/i;
i += 2;
}
return count;
}
public static double ji(int n){
int i = 1;
double count=0.0;
while(i<=n){
count += 1.0/i;
i += 2;
}
return count;
}
}