Java - 求和

作者: 追风剑007 | 来源:发表于2017-12-26 10:32 被阅读0次

计算 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);
    }
}

相关文章

网友评论

    本文标题:Java - 求和

    本文链接:https://www.haomeiwen.com/subject/bxedgxtx.html