Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ผลรวมอนุกรม 1/1 + (1+2)/(1×2) + (1+2+3)/(1×2×3) + ... จนถึง n พจน์ใน C++


ภาพรวมปัญหา

หาผลรวมของอนุกรม 1/1 + (1+2)/(1×2) + (1+2+3)/(1×2×3) + ... จนถึง n พจน์

ตัวอย่าง

Input: n = 3
Output: 3.5
Explanation: 1/1 + 3/2 + 6/6 = 1 + 1.5 + 1 = 3.5

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

double calcSeriesSum(int n) {
    double result = 0.0;
    int sum = 0, prod = 1;
    for (int i = 1; i <= n; i++) {
        sum += i;
        prod *= i;
        result += (double)sum / prod;
    }
    return result;
}

int main() {
    int n = 12;
    cout << "Sum = " << calcSeriesSum(n);
    return 0;
}

ผลลัพธ์

Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto 12 terms is 4.07742