编写一个函数,输入n为偶数时,调用方法求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n

需求:编写一个函数,输入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);
        }
    }
}

 方法二:

package stage3;

import java.util.Scanner;

public class Test1 {

    public void sum(int n){
        double s = 0;
        if(n % 2 == 0){
            for(int i = 2; i<=n;i+=2){
                s += 1.0/i;
            }
        }else{
            for(int i = 1; i<=n;i+=2){
                s += 1.0/i;
            }
        }
        System.out.println("和:"+s);
    }
    public static void main(String[] args) {
        // 奇偶数和
        Scanner input = new Scanner(System.in);
        System.out.println("输入一个数字:");
        int n = input.nextInt();
        new Test1().sum(n);;
    }

}

 

posted @ 2019-05-11 19:43  Geek张东坡  阅读(2178)  评论(0编辑  收藏  举报