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