输入一个正整数n,计算1-1/4+1/7-1/10+1/13-1/16+…前n项之和。

代码:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int n;

        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();

        double sum=0;
         for(int i=0;i<n;i++)
        {
            sum+=Math.pow(-1,i)*1/(i*3+1);
        }
         System.out.println(sum);
    }
}
0

Leave a Reply

Your email address will not be published.