using System;
class Program
{
static void Main(string[] args)
{
double balance, interestRate, targatebalance;
Console.WriteLine($"what you have balance now?");
balance=Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"what is your current aunnal interest rate (in %)?");
interestRate=1+Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"what your targatebalance? ");
targatebalance=Convert.ToDouble(Console.ReadLine());
int totalYears = 0;
if(balance>targatebalance) //让循环至少循环一次!
do
{
balance *=interestRate;
++totalYears;
}
while (balance < targatebalance); //do-while循环当while(false)时自动结束退出循环 //while循环while与do-while循环最大的区别就是while循环中的bool测试是在最开始,如果bool测试不通过则循环不会开始运行。do-while循环则是在循环一次后开始bool测试,如果不通过则结束循环
Console.WriteLine($"in {totalYears} year{(totalYears == 1 ? " " : "s")}"+$"you will have {targatebalance}."); //三元运算符
Console.ReadKey();
}
}
本文上部分使用do-while循环
do-while循环和while循环的区别已经在文中注释
//do-while循环当while(false)时自动结束退出循环 //while循环while与do-while循环最大的区别就是while循环中的bool测试是在最开始,如果bool测试不通过则循环不会开始运行。do-while循环则是在循环一次后开始bool测试,如果不通过则结束循环
接下来作者介绍另外一种循环for循环
using System;
class Program
{
static void Main(string[] args)
{
double balance, interestRate, targatebalance;
Console.WriteLine($"what you have balance now?");
balance=Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"what is your current aunnal interest rate (in %)?");
interestRate=1+Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"what your targatebalance? ");
targatebalance=Convert.ToDouble(Console.ReadLine());
int totalYears = 0;
int furtherYears = 100;
for (int i = 0; i<furtherYears&&balance<targatebalance; i++)
{
balance*=interestRate;
totalYears++;
}
//三元运算符
Console.WriteLine($"after {totalYears} year{(furtherYears == 1 ? " " : "s")}" + $" you will get the {targatebalance}!");
Console.ReadKey();
}
}
这里使用for循环
顺带提一句 ,由于作者水平有限,这里我令furtherYears=100,因为我觉得100年已经很大了。但是我在想如何让further等于某个数,让他自动计算,不用手动赋值确定循环次数。
这里有待商议,等我学会这种技术我再重新发一下。现在23.10了有点困了