流程控制-循环-do循环
do循环以下述方式执行:执行标记为循环的代码,然后进行一个布尔测试,如果测试的结果位true,就再次执行这段代码。当测试结果为false时退出循环。
do循环的结构如下:
do
{
<code to be looped>
}while(<test>);
其中计算<test>会得到一个布尔值。
提示,while语句后面的分好是必须有的,如果没有它,会产生一个错误。
例如,使用该结构可以把从1~10的数字输出到一列上:
int i = 1;
do
{
Console.WriteLine("{0}",i++);
}while(i <= 10);
在把i的值写到屏幕上后,使用后缀形式的++运算符递增i的值,所以需要检查一下i<=10,把10也包含在输出到控制台的数字中。
下面做一个例子。该段代码计算了一个账户在10年后的结余。这次使用一个循环,根据起始的金额和利率,计算该账户的金额要花多长时间才能达到某个指定的数值。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication7
{
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;
do
{
balance *= interestRate;
++totalYears;
} while (balance < targetBalance);
Console.WriteLine("In {0} year{1} you'll have a balance of {2}.",totalYears,totalYears == 1 ? "" : "s",balance);
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication7
{
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;
do
{
balance *= interestRate;
++totalYears;
} while (balance < targetBalance);
Console.WriteLine("In {0} year{1} you'll have a balance of {2}.",totalYears,totalYears == 1 ? "" : "s",balance);
Console.ReadKey();
}
}
}