【Java例题】4.1 级数求和1

1. 计算级数之和: y=1-1/2+1/4-1/8+...+ (-1)^(n-1)/2^(n-1)。 这里的"^"表示乘方。

 1 package chapter4;
 2 import java.util.*;
 3 
 4 public class demo1 {
 5     public static void main(String[] args) {
 6         Scanner sc=new Scanner(System.in);
 7         int n=sc.nextInt();
 8         double y=0;
 9         for(int i=1;i<=n;i++) {
10             y=y+Math.pow(-1, i-2)/Math.pow(2, i-1);
11         }
12         System.out.println("y="+y);
13     }
14 }
原文地址:https://www.cnblogs.com/LPworld/p/10723962.html