流程控制-循环-while循环
while循环非常类似于do循环,但有一个重要的区别:while循环中的布尔测试是在循环开始时进行,而不是最后。如果测试结果为false,就不会执行循环。程序会直接跳转到循环后面的代码。
while循环以下述方式指定:
while(<test>)
{
<code to be looped>
}
它使用的方式与do循环几乎完全相同,例如:
int i = 1;
while(i <= 10)
{
Console.WriteLine("{0},i++");
}
这段代码的执行结果与前面的do循环相同,它在一列中输出从1~10的数字。
下面使用while循环修改上次的示例。
using System;
using System.Collections.Generic;
using System.Text;
namespace while循环
{
class Program
{
static void Main(string[] args)
{
double balance, interestRate, targetBalance;
Console.WriteLine("What is your current balance?");
balance = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What is your current annual interest rate (in &)?");
interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;
Console.WriteLine("What balance would you like to have?");
targetBalance = Convert.ToDouble(Console.ReadLine());
int totalYears = 0;
while (balance < targetBalance)
{
balance *= interestRate;
++totalYears;
}
Console.WriteLine("In {0} year{1} you'll hava a balance of {2}.",totalYears,totalYears == 1 ? "" : "s",balance);
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace while循环
{
class Program
{
static void Main(string[] args)
{
double balance, interestRate, targetBalance;
Console.WriteLine("What is your current balance?");
balance = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What is your current annual interest rate (in &)?");
interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;
Console.WriteLine("What balance would you like to have?");
targetBalance = Convert.ToDouble(Console.ReadLine());
int totalYears = 0;
while (balance < targetBalance)
{
balance *= interestRate;
++totalYears;
}
Console.WriteLine("In {0} year{1} you'll hava a balance of {2}.",totalYears,totalYears == 1 ? "" : "s",balance);
Console.ReadKey();
}
}
}