C++——循环
“愚公移山”之while循环
使用场合:
当需要反复执行某些“过程”时,就可以使用while循环。
移山,移到什么时候?
只要山还在,就一直挖!
while (门前的山还在) {
一直挖
}
使用方法
while (条件) {
语句1
语句2
.......
}
强烈建议,无论循环体内有几条语句,都使用{}
break的作用
跳出所在的循环。
死循环
有些场合(比如,游戏引擎的主循环, 就是一个死循环)
更多场合,需要避免死循环。
demo:
1+2+3+4+...100
#include <iostream> #include <Windows.h> #include <string> using namespace std; int main(void) { int i = 1; int s = 0;
while (i<=100) { s += i; i++; } cout << "s=" << s << endl; system("pause"); return 0; } |
流程图
从功能上,for循环和while循环是完全等效的!
"后羿射日"之for循环
使用场合
在循环次数已经确定的情况下,使用for循环更方便!
射掉9个太阳即可。
使用方法
for (表达式1; 表达式2;表达式3){
循环体
}
说明:
表达式1: 为循环做准备
表达式2: 循环条件
表达式3: 改变循环计数
注意:
表达式1、表达式2、表达式3, 这3个表达式的任意一个或多个,都可以省略!
但是其中的“;”不可以省略!
for (; ; ) {
循环体
}
相当于:
while (1) {
循环体
}
for循环的表达式1
在C89标准中,表达式1不能定义变量
在C99标准和C++中,表达式1可以定义变量
表达式1中定义的变量,仅在for循环中有效。
流程图
for (表达式1; 表达式2;表达式3){
循环语句
}
for 循环的次数控制:
for (int i=0; i<10; i++) { ... } //常用方式
for (int i=1; i<=10; i++) { ... } //较少使用
使用for循环实现“后裔射日”
#include <iostream> #include <Windows.h> #include <string> using namespace std; //后羿射日 int main(void) { for (int i=1; i<=9; i++) { cout << "射第" << i << "个太阳" << endl; } system("pause"); return 0; } |
for和while的选择
1.当已经确定了循环次数时,建议使用for
2.其他情况,可以使用for ,也可以使用while, 建议使用while
使用for循环实现1+2+3+...100 = ?
#include <iostream> #include <Windows.h> #include <string> using namespace std; int main(void) { int s = 0; //1 + 2 + 3 + ... 100 for (int i=1; i<=100; i++) { s += i; } cout << s << endl; system("pause"); return 0; } |
"不服就干-直接干"之do-while循环
使用场合:
先执行一次循环体,然后再判断条件,以判定是否继续下一轮循环!
即:至少执行一次循环体!
使用方法
do {
循环体
} while (条件)
流程图:
使用do-while计算 1+2+3+...100
#include <iostream> #include <Windows.h> #include <string> using namespace std; int main(void) { int s = 0; int i = 1; do { s += i; i++; } while(i<=100); cout << s << endl; system("pause"); return 0; } |
特殊用法:【在特殊的宏定义中使用】
do {
// 循环体
} while(0);
posted on 2022-10-16 11:23 会飞的鱼-blog 阅读(23) 评论(0) 编辑 收藏 举报 来源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!