零基础学Java语言

Java - 求和

2017-12-26  本文已影响0人  追风剑007

计算 f(n) = 1 - 1/2 + 1/3 - 1/4 +... + 1/n

有三种方法:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        int result = 0;
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        double sum = 0.0;
        int sign = 1;
        for (int i=1;i<=n;i++) {
            sum = sum + sign*1.0/i;
            sign = -sign;
        }
        //output a number with 2 decimal
        System.out.printf("%.2f",sum);
    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        int result = 0;
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        double sum = 0.0;
        int sign = 1;
        for (int i=1;i<=n;i++, sign = -sign) {
            sum = sum + sign*1.0/i;
            sign = -sign;
        }
        //output a number with 2 decimal
        System.out.printf("%.2f",sum);
    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        int result = 0;
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        double sum = 0.0;
        for (int i=1;i<=n;i++) {
            if (i%2==1)
            {
                sum = sum + 1.0/i;
            }
            else
            {
                sum = sum - 1.0/i;
                }
            
        }
        //output a number with 2 decimal
        System.out.printf("%.2f",sum);
    }
}
上一篇下一篇

猜你喜欢

热点阅读