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

ผลรวมอนุกรม 0.7, 0.77, 0.777, ... จนถึง n พจน์ใน C++


ภาพรวมปัญหา

หาผลรวมของอนุกรม 0.7 + 0.77 + 0.777 + ... จนถึง n พจน์

ตัวอย่าง

Input: n = 4
Output: 3.0247
Explanation: 0.7 + 0.77 + 0.777 + 0.7777 = 3.0247

การ 유도สูตร

อนุกรม = 7/9 × [9n - 1 + 10⁻ⁿ]

หรือประมาณการ: 0.08641 × (9n - 1) + 10⁻ⁿ

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

#include <iostream>
#include <math.h>
using namespace std;

float calcSeriesSum(int n) {
    return (0.08641 * (9*n - 1) + pow(10, -n));
}

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

ผลลัพธ์

The sum of series 0.7, 0.77, 0.777, ... upto n terms is 3.80205