ภาพรวมปัญหา
หาผลรวมอนุกรม: Σ aⁱ/i! จาก i=1 ถึง n
ตัวอย่าง
a = 3, n = 4 → 3/1 + 9/2 + 27/6 + 81/24 = 3 + 4.5 + 4.5 + 3.375 = 15.375
วิธีแก้ปัญหา: ใช้พจน์ก่อนหน้าคำนวณพจน์ถัดไป
termᵢ = termᵢ₋₁ × a/i
โค้ด C++
#include <iostream>
using namespace std;
float calcSeriesSum(int a, int n) {
float sumVal = 0, term = 1;
for (float i = 1; i <= n; i++) {
term *= a / i;
sumVal += term;
}
return sumVal;
}
int main() {
int a = 3, n = 4;
cout << "The sum of the series is " << calcSeriesSum(a, n);
return 0;
}
ผลลัพธ์
15.375
หมายเหตุ
อนุกรมนี้เข้าใกล้ eᵃ - 1 เมื่อ n → ∞