循环直到资本加倍c#

时间:2013-02-18 10:43:09

标签: c# console-application

我想创建一个具有给定初始资本和固定年度百分比率(利息)的循环,该循环打印出当前年度的当前资本,直至并包括资本加倍的年份。

例如,初始资本为3000,利息为12。

//3000*(1 + 12 / 100) = 3360

output
year 1 = 3360
year 2 = 3763.2
year 3 = 4214.78
year 4 = 4720.55
year 5 = 5287,02
year 6 = 5921,46
//end (when the initial capital(3000) has doubled (6000))

我需要帮助的是创建一个循环,它将计算并显示输出,直到资本加倍使用for循环或while循环。输出不必像示例那样类似。

这是我到目前为止创建的代码:

double initialcapital = 0;
double interest = 0;
int year = 0;
double capital = 0;

Console.Write("Initial capital: ");
initialcapital = int.Parse(Console.ReadLine());

Console.Write("Interest: ");
interest = int.Parse(Console.ReadLine());

capital = initialcapital * (1 + interest / 100);
year = year + 1
Console.Writeline(capital);

2 个答案:

答案 0 :(得分:1)

 void displayCapital(double initalcapital, double interest){
     int year = 1;
     double capital = initialcapital;

     while(initialcapital > capital / 2) {
         Console.Write("Initial capital: ");
         initialcapital = int.Parse(Console.ReadLine());

         Console.Write("Interest: ");
         interest = int.Parse(Console.ReadLine());

         capital = initialcapital * (1 + interest / 100);
         year = year + 1
         Console.Writeline(capital);
     }
}

只需调用displayCapital(3000,12);你已经完成了

答案 1 :(得分:1)

如果您想在金额加倍之前找到确切的年数,可以使用:

double exactYears = Math.Log(2) / Math.Log((100 + interest) / 100);

否则以下内容适用于您:

double initialCapital = 0;
double interest = 0;
int year = 0;
double capital = 0;

Console.Write("Initial capital: ");
initialCapital = int.Parse(Console.ReadLine());

Console.Write("Interest: ");
interest = int.Parse(Console.ReadLine());
capital = initialCapital;

while (capital < initialCapital * 2)
{
    capital = capital * (1 + interest / 100);
    year = year + 1;

    Console.WriteLine("Years: " + year);
    Console.WriteLine("Capital: " + capital);
}

Console.WriteLine("Years: " + year);
Console.WriteLine("Capital: " + capital);

double exactYears = Math.Log(2) / Math.Log((100 + interest) / 100);
Console.WriteLine(string.Format("Capital doubled in exactly: {0:0.000} years", exactYears));