目录
P31程序流程结构-循环结构-while语句
P32程序流程结构-循环结构案例-猜数字
P33程序流程结构-循环结构-dowhile语句
P34程序流程结构-循环结构案例-水仙花数
P35程序流程结构-循环结构-for循环
P36程序流程结构-循环结构案例-敲桌子
P31程序流程结构-循环结构-while语句
while循环语句
作用:满足循环条件,执行循环语句
语法: while(循环条件){ 循环语句 }
解释:只要循环条件的结果为真,就执行循环语句
示例:
#include <iostream>
using namespace std;
int main() {
//while循环
//在屏幕中打印0~9这十个数字
int i = 0;
//while在()中填入循环条件
//注意事项:在写循环一定要避免死循环的出现
while (i < 10) {
cout << i << endl;
i++;
}
system("pause");
return 0;
}
运行后的结果为:
P32程序流程结构-循环结构案例-猜数字
案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。
#include <iostream>
using namespace std;
//time系统时间头文件包含
#include <ctime>
int main() {
//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样
srand((unsigned int)time(NULL));
//1、系统生成随机数
int num = rand() % 100 + 1;//rand()%100:生成0~99的随机数
//2、玩家进行猜测
int val = 0;
//3、判断玩家猜测
while (1) {
cin >> val;
if (num > val) {
cout << "过小" << endl;
}
else if (val > num) {
cout << "过大" << endl;
}
else {
cout << "恭喜你猜对了" << endl;
break; //可以利用该关键字来退出当前循环
}
}
//猜对 退出游戏
//猜错 提示猜测的结果 过大或者过小 重新返回第二步
system("pause");
return 0;
}
P33程序流程结构-循环结构-dowhile语句
作用:满足循环条件,执行循环语句
语法:do{ 循环语句 } while(循环条件);
注意:与while的区别在于==do...while会先执行一次循环语句==,再判断循环条件
示例:
#include <iostream>
using namespace std;
int main() {
//do while循环
//在屏幕中打印0~9这十个数字
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 10);
system("pause");
return 0;
}
运行后的结果为:
P34程序流程结构-循环结构案例-水仙花数
案例描述:水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身
例如:1^3 + 5^3+ 3^3 = 153
请利用do...while语句,求出所有3位数中的水仙花数
#include <iostream>
using namespace std;
int main() {
int num = 100;
do {
int ge = 0;
int shi = 0;
int bai = 0;
ge = num % 10;
shi = num / 10 % 10;
bai = num / 100;
if (ge * ge * ge + shi * shi * shi + bai * bai * bai == num) {
cout << num << endl;
}
num++;
} while (num < 1000);
system("pause");
return 0;
}
运行后的结果为:
P35程序流程结构-循环结构-for循环
作用:满足循环条件,执行循环语句
语法:for(起始表达式;条件表达式;末尾循环体){循环语句;}
示例:
#include <iostream>
using namespace std;
int main() {
//for循环
//从数字0打印到数字9
for (int i = 0; i < 10; i++) {
cout << i << endl;
}
system("pause");
return 0;
}
详解:
运行后的结果为:
注意:for循环中的表达式,要用分号进行分隔
总结:while , do...while, for都是开发中常用的循环语句,for循环结构比较清晰,比较常用
P36程序流程结构-循环结构案例-敲桌子
案例描述:从1开始数到数字50, 如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子及其对应的数字
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 50; i++) {
if (i % 10 == 7 || i / 10 % 10 == 7 || i % 7 == 0) {
cout << "敲桌子,此时的数字为:"<<i << endl;
}
}
system("pause");
return 0;
}
运行后的结果为: