1.while loop
- Format:
while(循环条件){
循环体;
}
- In the loop, we control the number of loops by controlling variables.
Three elements of loop:
initial value of loop variable,
judgment of loop variable,
update of loop variable
eg1:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while(i <= 10)
{
cout <<"小人本住在苏州的城边..\t第"<<i<<"遍\n";
i++;
}
return 0;
}
Output:
小人本住在苏州的城边.. 第1遍
小人本住在苏州的城边.. 第2遍
小人本住在苏州的城边.. 第3遍
小人本住在苏州的城边.. 第4遍
小人本住在苏州的城边.. 第5遍
小人本住在苏州的城边.. 第6遍
小人本住在苏州的城边.. 第7遍
小人本住在苏州的城边.. 第8遍
小人本住在苏州的城边.. 第9遍
小人本住在苏州的城边.. 第10遍
eg2:
#include <iostream>
using namespace std;
int main()
{
//目的:使用循环计算1-100的和
int num=1;//循环变量的初值
int sum=0;
while(num<=100) //循环变量的判断
{
sum+=num;
num++;//循环变量的更新
}
cout<<sum<<endl;
return 0;
}
eg3
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
//目的:输入密码,3次都输入错误退出登录
int i=1;
string password;
while(i<=3)
{
cout<<"请输入密码:"<<endl;
cin>>password;
if(password!="123456"&&i==3)
{
cout<<"3次密码输入错误,系统强制退出"<<endl;
exit(0);//0是错误码
}
else if(password=="123456")
{
break;
}
i++;
}
cout<<"登陆成功!"<<endl;
return 0;
}
Exercises:
1.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int k=2;
int i=0;
while(k=1)
{
k=k-1;
cout<<"第"<<++i<<"次循环"<<endl;
}
return 0;
}
This is an infinite loop. Because k=1
it is an assignment operation and the return value is 1, while(1) will be executed. It is an infinite loop.
2. Determine whether the statement output is:
int n=0;
while(n++<=2);
cout<<n;
The answer is 4.
Analysis: n++<=2, so n=2 when n enters for the last time, and then n++ is executed, that is, n=3; don’t forget to make a
judgment when finally jumping out of the loop, and execute n++ again. <=2 statement, n=3 at this time, does not meet the condition, but the ++ statement still needs to be executed, that is, n=n+1=4.
example:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//使用循环模拟拳皇对战
int hp1=100;
int hp2=100;
int attack1=0;
int attack2=0;
int randNum;
srand(time(NULL));//更新随机种子
while(hp1>=0&&hp2>=0)
{
//玩家出招,可以采用随机数是奇数还是偶数决定谁先攻击
randNum=rand();
if(randNum % 2==1)
{
//随机产生5到15的随机数
attack1=(int)(5 + 10 *rand()/(RAND_MAX+1));
attack2=(int)(5 + 10 *rand()/(RAND_MAX+1));
hp2-=attack1;
hp1-=attack2;
}
else
{
attack2=(int)(5 + 10 *rand()/(RAND_MAX+1));
attack1=(int)(5 + 10 *rand()/(RAND_MAX+1));
hp1-=attack2;
hp2-=attack1;
}
}
cout<<"玩家1:"<<hp1<<endl;
cout<<"玩家2:"<<hp2<<endl;
return 0;
}