(原创)c#学习笔记04--流程控制04--循环02--while循环

4.4.2 while循环

  while循环非常类似于do循环,但有一个明显的区别:while循环中的布尔测试是在循环开始时进行,而不是最后。如果测试结果为false,就不会执行循环。程序会直接跳转到循环之后的代码。

  按下述方式指定while循环:

while (<Test>) 
{ 
    <code to be looped> 
}

  对上一章节中的示例,用while循环实现一遍,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch04Ex05
{
    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 have a balance of {2}.", totalYears, totalYears == 1 ? "":"s", balance );
            
            if( 0 == totalYears ) {
                Console.WriteLine( "To be honest, you really didn't need to use this calculator." );
            }
            
            Console.ReadKey();
        }
    }
}

  运行结果如下:

  可以检查用户输入,确保目标余额大于起始余额。此时,可以把用户输入部分放在循环中,如下所示:

do { 
    targetBalance = Convert.ToDouble(Console.ReadLine()); 
    if (targetBalance <= balance) 
    Console.WriteLine("You must enter an amount greater than " + 
        "your current balance!\nPlease enter another value."); 
} while (targetBalance <= balance); 

  这将拒绝接受无意义的值。

  在设计应用程序时,用户输入的有效性检查是一个很重要的主题。

posted @ 2015-10-21 21:01  星月相随  阅读(291)  评论(0编辑  收藏  举报