这种方法也不错:
- import java.util.Scanner;
- /**
- 思路:
- 1,使用Scanner接收一个数值,并且把这个数值赋给int型的变量
- 2,判断这个数值是否为偶数,如果为偶数调用getEvenSum()方法,否则调用getOddSum()方法
- 3,编写方法
- */
- public class Sum
- {
- public static void main(String[] args)
- {
- Scanner sa = new Scanner(System.in);
- int number = sa.nextInt();
- if(number%2==0)
- {
- System.out.println(getEvenSum(number));
- }else
- {
- System.out.println(getOddSum(number));
- }
- }
- public static double getEvenSum(int number)
- {
- double temp = 0;
- for(int i = 2;i <= number;i+=2)
- {
- System.out.println(i);
- temp += (double)1/(double)i;
- }
- return temp;
- }
- public static double getOddSum(int number)
- {
- double num = 0;
- for(int j = 1;j <= number;j+=2)
- {
- num += (double)1/(double)j;
- }
- return num;
- }
- }
复制代码 |