【Java例题】4.2 级数求和2

2. 计算级数之和: y=1/1!*x-1/3!*x^3+1/5!*x^5+...+ (-1)^n/(2n+1)!*x^(2n+1)。 这里的"^"表示乘方,"!"表示阶乘。x和n由键盘输入

package chapter4;
import java.util.*;

public class demo2 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("输入n");
        int n=sc.nextInt();
        System.out.println("输入x");
        int x=sc.nextInt();
        double y=0;
        for(int i=0;i<n;i++) {
            y=y+Math.pow(-1, i)/(jiecheng(2*i+1)*Math.pow(x, 2*i+1));
        }
        System.out.println("y="+y);
    }
    
    static int jiecheng(int a) {
        int b=1;
        for(int i=1;i<=a;i++) {
            b=b*i;
        }
        return b;
    }
}

 

posted @ 2019-04-17 15:40  海底淤泥  阅读(327)  评论(0编辑  收藏  举报