[英]How can I create the compound interest formula in C++ without a math library?
我一直在嘗試完成一項要求我運行復利公式的作業,但我只能使用 iomainip 和 iostream 庫。
do (cout << BaseMembershipFee * pow((ONE+(GoldRate/CompoundMonthly),(CompoundMonthly*years)) << years++) << endl;
while (years < 11);
這適用於數學庫(我認為),但我不知道如何在沒有 pow 的情況下制作它。
變量:
const float BaseMembershipFee = 1200, GoldRate = 0.01, CompoundMonthly = 12, ONE = 1;
float years = 1;
在您的問題中,它指出年 = 1。基於 do while() 循環,我懷疑您的意思是顯示年 = 10。
下面的代碼有一個函數來計算每個時期的復利,在你的情況下是每個月。
然后,因為看起來你被要求在每年年底計算臨時金額,所以我們有第二個 for 循環。
#include<iostream>
float CompountInterestMultiplier(float ratePerPeriod, float periods) {
float multiplier = 1.0;
for (int i = 0; i < periods; i++) {
multiplier *= (1.0 + ratePerPeriod);
}
return multiplier;
}
int main() {
const float BaseMembershipFee = 1200;
const float GoldRate = 0.01; // represents annual rate at 1.0%
const float periodsPerYear = 12.0; // number of compounds per year. Changed the name of this from compoundsMonthly
const float ONE = 1.0; // Did not use this
const float years = 10.0; // I think you have a typo
// and wanted this to be 10
float ratePerPeriod = GoldRate / periodsPerYear;
// If you want to print the value at the end of each year,
// then you would do this:
float interimValue = BaseMembershipFee;
for (int year = 0; year < 11; year++) {
interimValue = BaseMembershipFee *
CompountInterestMultiplier(ratePerPeriod, periodsPerYear * year);
std::cout << "Value at end of year " << year << ": $" << interimValue << std::endl;
}
}
Here is the output:
Value at end of year 0: $1200
Value at end of year 1: $1212.06
Value at end of year 2: $1224.23
Value at end of year 3: $1236.53
Value at end of year 4: $1248.95
Value at end of year 5: $1261.5
Value at end of year 6: $1274.17
Value at end of year 7: $1286.97
Value at end of year 8: $1299.9
Value at end of year 9: $1312.96
Value at end of year 10: $1326.15
Process finished with exit code 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.