ต่อไปนี้เป็นโปรแกรม Java เพื่อค้นหาผลรวมของซีรีส์ -
1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!
ตัวอย่าง
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));
}
} ผลลัพธ์
The sum of the series is : 2.7166666666666663
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'pattern_sum' ฟังก์ชันนี้ใช้ค่า double valuednumber เป็นพารามิเตอร์ และวนซ้ำค่าและคำนวณค่าอนุกรมของ (1/1! + 2/2! +..) เป็นต้น ในฟังก์ชันหลัก ค่าจะถูกกำหนดและฟังก์ชัน 'pattern_sum' จะถูกเรียกโดยข้ามค่านี้ เอาต์พุตจะแสดงบนคอนโซล