首页 技术 正文
技术 2022年11月11日
0 收藏 800 点赞 4,198 浏览 730 个字
  • if 与 while 的主要区别:if 只判断和执行一次,而 while 却代表着一个循环,执行多少次,要视情况而定;

  • 两种情况(A、B)都会让循环体执行:

    while A or B:
  • 两种情况(A、B)都会退出循环体:

    while !A and !B:

1. 循环体内的变量

  • 在循环体外初始化 —— 表示,累计其值

    count = 0;
    while True:
    count += 1
  • 循环体内初始化 —— 表示,每次过去的值不会被累加:

    while True:
    sum = 0
    ...

2. while 循环与 for 循环的转换

int i = 0;
for (; cond; ++i) int i = 0;
while (cond) {
...
++i;
}

3. 循环内某判断及处理仅做一次

int cnt = 0;
while (true) { if (cnt++ == 1) cout << "."; ... }

4. while 中的 if(){ return;},突然死亡法

A;
while(B)
{ ... }
C;
// 想要执行到 C;必须经过 while()
// 而经过 while(), 可以 B 成立,进入循环
// 也可以 B 不成立,压根没有进入循环
// 但走到 C 的前提一定是 B 不成立了

5. while (true)

while (true){
if (条件){
...
}
}

会等价于:

while (条件){
...
}

6. while 循环:表消耗(consume)

为什么 while 循环可以表示消耗的含义呢?当 while 中的条件成立时,while 循环会一直执行下去,直到 while 中的条件不成立,也即会消耗掉所有使得条件成立的状态。

比如字符串匹配问题,

int pos = 0;
while ((pos < str.size() && pos < pattern.size()) && (pattern[pos] == '?' || pattern[pos] == str[pos]))
++pos;
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,089
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,566
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,415
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,187
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,823
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,906