首页 > 解决方案 > 显示每月复利值的方法?

问题描述

我是面向对象编程的新手,我需要想出一种方法来显示每个月的值,这些值由特定的利率复合而成。我最初是在考虑一个列表,并将列表中的每个值都与前一个值相结合,但我不知道如何实际实现这一点。

目前,用户可以使用以下公式指定他们的初始投资并在期末获得最终价值:

double initialInvestmentReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 12 * numberOfYears + (numberOfMonths)) * initialInvestment;

然后,用户应该能够指定每月复利的固定每月投资,并在最后计算。要找到仅一个月的每月回报,这是我使用的公式:

double monthlyInterestReturn = Math.Pow(1 + ((InterestRate / 100) / 12), 1) * monthlyInvestment;

这是我目前尝试使用的方法:

ArrayList monthlyValues = new ArrayList();
            int counter = 0;

            while (0 == 0)
            {
                monthlyValues.Add(monthlyInterestReturn);

                if (monthlyValues.Count == numberOfMonths + (numberOfYears * 12))
                {
                    break;
                }

            }

            foreach (double d in monthlyValues)
            {
                counter++;
                double var = monthlyInvestment * counter;
                double result = Math.Pow(1 + ((InterestRate / 100) / 12), counter) * var;

                rtfTestBox.Text += result.ToString("#.##") + Environment.NewLine;

            }

由于我被完全教过的唯一适用的数据结构是 Array/ArrayList(我被告知它已被 SO 用户过时)我试图找到一种方法将 AL 中的下一个值设置为复合值以前的索引值,但无济于事。我得到的输出低于你可以看到的不太正确。

//100 invested per month for 3 years 0 months at 12% annual interest:
    101
    204.02
    309.09
    416.24
    525.51
    636.91
    750.49
    866.29
    984.32
    1104.62
    1227.24
    1352.19
    1479.52
    1609.26
    1741.45
    1876.13
    2013.32
    2153.07
    2295.41
    2440.38
    2588.02
    2738.37
    2891.47
    3047.36
    3206.08
    3367.67
    3532.16
    3699.61
    3870.06
    4043.55
    4220.11
    4399.81
    4582.68
    4768.76
    4958.11
    5150.77

该项目是 Visual Studio 中的 .NET C# 应用程序。

任何帮助将不胜感激,如有必要,我非常乐意提供更多细节。

提前致谢!

标签: c#.netlistvisual-studiodata-structures

解决方案


正如您所提到的, ArrayList 已过时。c# 中的 goto 数据结构是List<T>. 当我们谈论金钱时,推荐的类型是小数,这避免了其他浮点类型的一些舍入问题。

对于这种情况,我们可以使用称为迭代器块的东西来更方便:

    public static IEnumerable<decimal> CompoundIntrest(decimal initialAmount, decimal yearlyIntrestRatePercent, decimal monthlyInvestmentRate)
    {
        var montlyIntrest = 1 + yearlyIntrestRatePercent / (1200);
        var currentAmount = initialAmount;
        while (true)
        {
            yield return currentAmount;
            currentAmount = currentAmount * montlyIntrest + monthlyInvestmentRate;                
        }
    }

叫像

        var amounts = CompoundIntrest(100, 12, 100).Take(36);
        foreach(var a in amounts)
        {
            Console.WriteLine(a.ToString("N1"));
        }

注意Take(36),这决定了从多少个月取值,防止无限循环。还有使用ToList方法将其转换为实际列表。


推荐阅读