一、簡介
只要給定條件為true,C#的while回圈陳述句會回圈重新執行一個目標的陳述句,
二、語法
C# while的語法:
while(回圈條件)
{
回圈體;
}
三、執行程序
程式運行到while處,首先判斷while所帶的小括號內的回圈條件是否成立,如果成立的話,也就是回傳一個true,則執行回圈體,執行完一遍回圈體后,再次回到回圈條件進行判斷,如果依然成立,則繼續執行回圈體,如果不成立,則跳出while回圈體,
在while回圈當中,一般總會有那么一行代碼,能夠改變回圈條件,使之終有一天不在成立,如果沒有那么一行代碼能夠改變回圈條件,也就是回圈體條件永遠成立,則我們將稱之為死回圈,
最簡單死回圈:
while(true)
{
}
四、特點
先判斷,在執行,有可能一遍都不執行,
五、實體
1.向控制臺列印100遍,下次考試我一定要細心.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
//需要定義一個回圈變數用來記錄回圈的次數,每回圈一次,回圈變數應該自身加1
int i = 1;
while (i<=100)
{
Console.WriteLine("下次考試我一定要細心\t{0}", i);
//每回圈一次,都呀自身加-,否則是死回圈
i++;
}
Console.ReadKey();
}
}
}
輸出結果

2.求1-100之間所有整數的和
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
//求1-100之間所有整數的和
//回圈體:累加的程序
//回圈條件:i<=100
int i = 1;
int sum = 0; //宣告一個變數用來存盤總和
while (i<=100)
{
sum += i;
i++;
}
Console.WriteLine("1-100之間所有整數的和為{0}",sum);
Console.ReadKey();
}
}
}
輸出結果

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/115468.html
標籤:C#
