Dưới đây là chương trình Java để tìm tổng của chuỗi:
1/1! + 2/2! + 3/3! + 4/4! + ... + n/n!
Ví dụ
import java.io.*;
import java.lang.*;
public class Demo {
public static double pattern_sum(double val) {
double residual = 0, factorial_val = 1;
for (int i = 1; i <= val; i++) {
factorial_val = factorial_val * i;
residual = residual + (i / factorial_val);
}
return (residual);
}
public static void main(String[] args) {
double val = 6;
System.out.println("The sum of the series is: " + pattern_sum(val));
}
}
Kết quả
The sum of the series is: 2.7166666666666663
Một lớp tên Demo chứa hàm 'pattern_sum'. Hàm này nhận tham số double, lặp qua giá trị và tính giá trị chuỗi (1/1! + 2/2! + ...) và seterusnya. Trong hàm main, giá trị được định nghĩa và hàm 'pattern_sum' được gọi bằng cách truyền giá trị này. Đầu ra được hiển thị trên console.