Bài học
Lưu code
Refresh
Xoay
Xem kết quả
/* Yêu cầu – Nhập vào số nguyên dương n (n > 0) từ cửa sổ màn hình console. – Sau đó, tính tổng S(n) = x + x^2/2! +…+ x^n/n! Giải thuật – Dùng vòng lặp do while() để bắt người dùng nhập lại giá trị n nếu nhập giá trị n <= 0 – Dùng phương thức Math.pow() tính lũy thừa. – Viết hàm tính n! – Dùng vòng lặp for để tính tổng S(n). */ package net.vncoding; import java.util.Scanner; import java.lang.Math; public class JavaCore { public static void main(String[] args) { int n; float x; float sum = 0f; Scanner sc; do { System.out.print("Input n = "); sc = new Scanner(System.in); n = sc.nextInt(); }while(n <= 0); System.out.print("Input x = "); x = sc.nextFloat(); for(int i = 1; i <= n; i++) { sum += Math.pow(x, i)/factorial(i); } System.out.println("Sum = " + sum); sc.close(); } public static long factorial(int n) { long sum = 1; for(int i = 1; i <= n; i++) { sum = sum * i; } return sum; } }
kết quả: