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

โปรแกรม C++ คำนวณปีที่ต้องใช้เพื่อให้เงินในธนาคารถึง X บาท ด้วยดอกเบี้ย 1%


คำอธิบายปัญหา

สมมติว่าเรามีตัวเลข X มีเงินในธนาคาร 100 บาท ธนาคารให้ดอกเบี้ยรายปี 1% คิดดอกเบี้ยทบต้นทุกปี (ใช้จำนวนเต็มเท่านั้น) ต้องการหาว่าต้องใช้กี่ปีถึงจะได้เงิน X บาท

ตัวอย่าง: X = 520 ผลลัพธ์คือ 213

ขั้นตอนการแก้ปัญหา

sum := 0
balance := 100
while balance < n ทำ:
    interest := balance / 100
    sum := sum + 1
    balance := balance + interest
คืนค่า sum

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

#include <bits/stdc++.h>
using namespace std;

int solve(int n){
    int sum = 0;
    int balance = 100;
    while (balance < n){
        int interest = balance / 100;
        sum = sum + 1;
        balance = balance + interest;
    }
    return sum;
}

int main(){
    int X = 520;
    cout << solve(X) << endl;
}

อินพุต

520

เอาต์พุต

213