首页 > 解决方案 > 尝试运行本地函数 C# 后没有结果

问题描述

我对 C# 完全陌生,我正在尝试编写一个函数来计算复利后某个金额何时翻倍(以n年为单位)。

现在,当我在 VS Code 中运行它时,我没有收到任何错误,但我也没有得到结果。到目前为止,这是我的代码:

using System;

int NumberOfYearsToDouble(int Amount, int InterestRate) {
    int NumberOfYears = 0;
    int Percentage;

    while (Amount < (Amount*2)) {
        Percentage = (Amount/100) * InterestRate;
        Amount = Amount + Percentage;
        NumberOfYears++;
    }
    return NumberOfYears;
}
NumberOfYearsToDouble(1000,8);
Console.WriteLine();

标签: c#

解决方案


您正在创建一个无限循环:

while (Amount < (Amount*2))

Amount将始终小于Amount*2, (除非Amount是负整数)。

您应该存储循环Amount*2之前的值while,以便它在Amount更改时保持不变:

int doubleAmount = Amount*2;
while (Amount < doubleAmount)

推荐阅读