简体   繁体   English

循环直到资本加倍c#

[英]loop until the capital has doubled c#

I want to create a loop that has a given initial capital and a fixed annual percentage rate (interest) that prints out the current capital for the current year up to and including the year in which the capital has doubled. 我想创建一个具有给定初始资本和固定年度百分比率(利息)的循环,该循环打印出当前年度的当前资本,直至并包括资本翻倍的年份。

for example the initial capital is 3000 and the interest is 12. 例如,初始资本为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))

what i need help with is to create a loop that will calculate and show the output until the capital has doubled with either a for loop or while loop. 我需要帮助的是创建一个循环,它将计算并显示输出,直到资本使用for循环或while循环加倍。 the output doesnt have to be like the example but something similar. 输出不必像示例,但类似的东西。

here is the code ive created so far: 这是我到目前为止创建的代码:

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);
 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);
     }
}

just call displayCapital(3000, 12); 只需调用displayCapital(3000,12); and you are done 你完成了

If you want to find the exact number of years before the amount doubles you can use this: 如果你想在金额加倍之前找到确切的年数,你可以使用:

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

Otherwise the following will work for you: 否则以下内容适合您:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM