存款复利计算器

时间:2021-03-16 16:37:13

标签: c#

用户输入错误 "100 12 1" 预期为 101 但为 100

怎么了?

static double Calculate(string userInput)
{
    var arrString = userInput.Split(' ');
    double initialAmount = double.Parse(arrString[0]);
    int interestRate = int.Parse(arrString[1]);
    int countMonth = int.Parse(arrString[2]);

    return initialAmount * Math.Pow((1 + interestRate / 12 / 100), countMonth);
}

1 个答案:

答案 0 :(得分:0)

您将一个整数除以一个整数 ((1 + interestRate / 12 / 100)):this produces an integer

要获得您期望的结果,请将 interestRate 强制转换为 int,或者像您对 initialAmount 所做的那样将其解析为 double:

static double Calculate(string userInput)
{
    var arrString = userInput.Split(' ');
    double initialAmount = double.Parse(arrString[0]);
    int interestRate = double.Parse(arrString[1]);
    // either do this  ^^^^^^

    int countMonth = int.Parse(arrString[2]);

    return initialAmount * Math.Pow((1 + (double)interestRate / 12 / 100), countMonth);
    // or do this                        ^^^^^^^^
}