while循环语句的作用:当循环条件满足时,执行循环语句。
语法:
while(循环条件){循环语句}
#include<iostream>
using namespace std;
int main()
{
//使用循环结构在黑窗口中输出0~9是个数
int 数 = 0;
while (数 < 10)
{
cout << 数 << endl;
数++;
}
system("pause");
return 0;
}
当()中的循环条件为真时就执行循环,结果为假时就停止循环(即条件成立时执行循环。不成立停止循环)。
*注意,在创建循环时要避免死循环的出现。
学了while循环语句后我们可以做一个小游戏
#include<iostream>
using namespace std;
int main()
{
//让用户来猜测数字
int shu = 0;
cout << "请您猜测数字" << endl;
//此算式为定义随机数,如时rand()%100为0~99,rand()%100+1的结果为0+1~99+1
int SHU = rand() % 100 + 1;
//让用户输入数字并提示猜测过大或过小
//同时猜错时让用户再次输入数字
while (1)//此为死循环,即结果为真就循环
{
cin >> shu;
if (shu < SHU)
{
cout << "猜测过小" << endl;
}
else if (shu > SHU)
{
cout << "猜测过大" << endl;
}
else
{
cout << "恭喜您猜对了" << endl;
break;
}
}
system("pause");
return 0;
}
rand()%100+1d 意义为从1~100里随机选择一个数(括号中没有种子时一般为42或41)