求和:1+1/2-1/3+1/4-1/5……+1/n

package com.jnwork;

import java.util.Scanner;

public class Sum {
	/**
	 * 1+1/2-1/3+1/4-1/5……+1/n求和
	 */
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个正整数N值:");
		int n=sc.nextInt();
		double sum=0;
		String data="";
		for (int i = 1; i <=n; i++) {
			if(i==1){
				sum=1;
				data=data+1;
			}
			else{
				if(i%2==1){
					data=data+("-1/")+i;
					sum=sum-1.0/i;
				}else{
					data=data+("+1/")+i;
					sum=sum+1.0/i;
				}
			}
		}
		System.out.println(data+"="+sum);
		}
}


package com.jnwork;

import java.util.Scanner;
/*
 * 1+1/2+1/3+1/4+......+1/n求和
 */
public class Sum2 {
	public static void main(String[] args) {
		 Scanner sc = new Scanner(System.in);
		 System.out.println("请输入正整数n:");
		 int n = sc.nextInt();
        double sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += (double) 1 / i;
        }
        System.out.println("和为:"+sum);
    }
}


posted @ 2017-11-24 08:48  ·卿欢·  阅读(1551)  评论(0编辑  收藏  举报