今天我們再來學學循環語句while 和do while
While和do while 就是根據條件進行循環
While (條件)
{
循環體
}
Do{
循環體
}while (條件)
本質的區別就在於是
while語句是先判斷是否符合條件符合再做
dowhile先做再判斷是否符合條件.
複製下面的代碼運行一下看看就知道區別了。
#include<iostream>
using namespace std;//用上這句話,就不用寫include<xxxx.h>的.h
void main(void)
{
int i;
i=1;
while(i < 1)
{
i++;
}
cout<<"while語句"<<endl;
cout<<"i=1;"<<endl;
cout<<"while(i <1)"<<endl;
cout<<"{"<<endl;
cout<<" i++;"<<endl;
cout<<"}"<<endl;
cout<<"結果:i = "<<i<<endl;
cout<<endl<<endl<<endl;
i=1;
do {
i++;
}while(i < 1);
cout<<"DO while語句"<<endl;
cout<<"i=1;"<<endl;
cout<<"do {"<<endl;
cout<<" i++;"<<endl;
cout<<"}while(i <1)"<<endl;
cout<<"結果:i = "<<i<<endl;
}
Do while 有時不小心就會出錯(因爲它是先做後判斷條件)
所以我推薦用while (個人觀點)
再介紹兩個函數
Break 直接結束循環(跳出循環語句)
Continue 跳過本次循環進行下一次循環(只要有下一次循環,就不會跳出循環語句)。
運行以下代碼就知道這兩者的區別
#include<iostream>
using namespace std;//用上這句話,就不用寫include<xxxx.h>的.h
void main(void)
{
int i;
i=1;
while(i < 1000)
{
i++;
break;
}
cout<<"break運行結果:i = "<<i<<endl;
i=1;
while(i < 1000)
{
i++;
continue;//只要它的後面沒代碼就不會有區別(可去掉)
}
cout<<"continue運行結果:i = "<<i<<endl;
}
好了今天就到這裏吧。