c++ - 在没有数学库的情况下,如何在 C++ 中创建复利公式?

标签 c++

我一直在努力完成一项要求我运行复利公式的作业,但我只能使用 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;

最佳答案

在您的问题中,它指出 years = 1。根据 do while() 循环,我怀疑您打算显示 years = 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

关于c++ - 在没有数学库的情况下,如何在 C++ 中创建复利公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53038015/

相关文章:

c++ - 在 C++ 代码中使用嵌入式汇编语言进行错误分析

c++ - 串口打开返回EAGAIN

c++ - 在 Visual Studio 调试中检查 STL 容器

c++ - 如何从 C++ 中的函数返回结构?

c++ - 模板中的类型转换

c++ - 包含 main 的 CMake Object Lib

C++:将 const char* 类型的字符串文字传递给字符串参数

C++ 和 SDL : Why can't I compile this program?

c++ - 当多个重载通过 SFINAE 时创建首选重载

c++ - Waitpid 等待已失效的子进程