需求:打印 0~9 这10个数字
#include
using namespace std;
int main() {
int num = 0;
// while 循环中 while 后面的括号()中 添加循环条件
// 然后 while 循环体中添加符合条件需要打印的语句或者是符合条件需要执行的语句
while (num < 10)
{
/* code */
cout << num << endl;
num++;
}
system("pause");
return 0;
}

系统随机生成一个 1 ~ 100 的数字,然后玩家猜:
如果猜对,则输出猜对了,并结束游戏;
如果猜错,输出玩家猜测的数字是大了还是小了。
#include
using namespace std;
int main() {
// 猜数字游戏:
int stand_num;
// 1.系统随机设置数字 1 ~ 100
// rand()%100 // 这样就会生成一个 0 ~ 99 的随机数
// 伪随机数?一直打印42
stand_num = rand()%100 + 1;
// cout << stand_num << endl;
// 2.玩家进行猜测,也就是获取玩家输入的数字
int user_num;
cout << "你要猜的数字:" << endl;
cin >> user_num;
// 3.对玩家猜测的数字与 [系统随机生成的数字] 进行判断是否一致,
// 如果猜对,直接输出 win ,游戏结束;
// 如果猜错,输出玩家猜测的数字相较于 [系统随机生成的数字] 的大小,进一步提示玩家。
while (user_num != stand_num) {
if (user_num > stand_num) {
cout << "大了" << endl;
}
else if (user_num < stand_num) {
cout << "小了" << endl;
}
cout << "你要猜的数字:" << endl;
cin >> user_num;
}
cout << "猜对了" << endl;
system("pause");
return 0;
}

或者是结合 while 和 break .
#include
using namespace std;
int main() {
// 猜数字游戏:
int stand_num;
// 1.系统随机设置数字 1 ~ 100
// rand()%100 // 这样就会生成一个 0 ~ 99 的随机数
// 伪随机数?一直打印42
stand_num = rand()%100 + 1;
// cout << stand_num << endl;
// 2.玩家进行猜测,也就是获取玩家输入的数字
int user_num;
// 3.对玩家猜测的数字与 [系统随机生成的数字] 进行判断是否一致,
// 如果猜对,直接输出 win ,游戏结束;
// 如果猜错,输出玩家猜测的数字相较于 [系统随机生成的数字] 的大小,进一步提示玩家。
while (1) {
cout << "你要猜的数字:" << endl;
cin >> user_num;
if (user_num > stand_num) {
cout << "大了" << endl;
}
else if (user_num < stand_num) {
cout << "小了" << endl;
}
else {
cout << "猜对了" << endl;
break;
}
}
system("pause");
return 0;
}
#include
#include
using namespace std;
int main() {
// 这里使用 time 上面必须得有 #include
srand((unsigned int) time(NULL));
int stand_num;
// 1.系统随机设置数字 1 ~ 100
// rand()%100 // 这样就会生成一个 0 ~ 99 的随机数
// 伪随机数?一直打印42
stand_num = rand()%100 + 1;
cout << stand_num << endl;
system("pause");
return 0;
}

作用:满足循环条件,执行循环条件
语法:do{ 循环语句 } while ( 循环条件 );
注意:与 while 的区别在于 do ··· while 会先执行一次循环语句,再判断循环条件
需求:在屏幕中输出 0 ~ 9 这10个数字。
#include
#include
using namespace std;
int main() {
int num = 0;
do {
cout << num << endl;
num++;
}
while (num < 10);
system("pause");
return 0;
}
