Java求1-1/2+1/3-1/4+1/5+...+1/n

代码如下

import java.util.Scanner;

public class fenshu {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       Scanner sc=new Scanner(System.in);
       while(sc.hasNext()) {
       int n=sc.nextInt();
       leijia a=new leijia();
       java.text.DecimalFormat   df   =new   java.text.DecimalFormat("0.000000");
      System.out.println(df.format(a.test(n)));
	}
	}
}
class leijia{
  double sumou=0.000000;
  double sumji=0.000000;
	public double test(int n) {
		
		 for(int i=1;i<=n;i++) {
			 if(i%2==0) {
				 sumou=sumou+(1.0/i);
			 }else {
				 sumji=sumji+(1.0/i);
			 }
		 }
		 return sumji-sumou;
		
	}
}

你可能感兴趣的:(Algorithm)