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

ผลรวมอนุกรมฮาร์มอนิกทั่วไปใน C++ (General Harmonic Series)

ภาพรวมปัญหา

หาผลรวมอนุกรมฮาร์มอนิกทั่วไป: 1/a + 1/(a+d) + 1/(a+2d) + ... + 1/(a+(n-1)d)

ตัวอย่าง

a = 3, d = 2, n = 5
อนุกรม: 1/3 + 1/5 + 1/7 + 1/9 + 1/11 ≈ 0.878211

วิธีแก้ปัญหา 1: วนลูป (Iterative)


float findSeriesSum(int a, int d, int n) {
    float sumVal = 0;
    for (float i = 1; i <= n; i++) {
        float term = 1.0f / (a + (i-1)*d);
        sumVal += term;
    }
    return sumVal;
}

วิธีแก้ปัญหา 2: Recursive


float findSeriesSum(int a, int d, int n) {
    if (n == 1) return 1.0f / a;
    float term = 1.0f / (a + (n-1)*d);
    return term + findSeriesSum(a, d, n-1);
}

โค้ด C++ เต็ม

#include <iostream>
using namespace std;

float findSeriesSum(int a, int d, int n) {
    float sumVal = 0;
    for (float i = 1; i <= n; i++) {
        float term = 1.0f / (a + (i-1)*d);
        sumVal += term;
    }
    return sumVal;
}

int main() {
    int n = 5, a = 3, d = 2;
    cout << "The sum of HP is " << findSeriesSum(a, d, n);
    return 0;
}

ผลลัพธ์

0.878211