While迴圈
在程式語言中,while迴圈(英語:)是一種控制流程的陳述。利用一個返回结果为布林值(Boolean)的表达式作為循环條件,当这个表达式的返回值为“真”(true)时,则反覆執行循环体内的程式碼;若表达式的返回值为“假”(false),则不再执行循环体内的代码,继续执行循环体下面的代码。
结构 |
---|
do-while |
while |
for |
foreach |
因為while迴圈在區塊內代碼被執行之前,先檢查陳述是否成立,因此這種控制流程通常被稱為是一種前測試迴圈(pre-test loop)。相對而言do while迴圈,是在迴圈區塊執行結束之後,再去檢查陳述是否成立,被稱為是後測試迴圈。
程式範例

while 迴圈
C/C++
unsigned int counter = 5;
unsigned long factorial = 1;
while (counter > 0)
{
factorial *= counter--; /*当满足循环条件(本例为:counter > 0)时会反复执行该条语句 */
}
printf("%lu", factorial);
VB
'这是一个用While循环的例子
dim counter as Integer
dim Tick as Integer
counter=5
tick=1
Print "Start"
while counter>0
counter=counter-tick
'循环语句
Wend
Print "End"
java
public static void main(str args[]){
while true{
System.out.println("Hello World!") //因为条件已经固定为常量true,所以就会不断执行循环体内的语句
}
int counter = 0 ;
while counter<5{
System.out.println("已经运行了"+counter+"次") //因为条件限定为counter不大于5,所以在counter不大于5的情况下会不断重复循环体中的内容
counter++;
}
}
Python語言
a = 0
while a <= 10 : #如果a沒有大於10就執行
a = a+1
print(a)
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.