zoukankan      html  css  js  c++  java
  • while 循环的理解

    • 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;
  • 相关阅读:
    投行风云:FO的酸甜苦辣【转】
    周末排毒
    LeetCode | Single Number II【转】
    Adding supplementary tables and figures in LaTeX【转】
    Algorithm | Tree traversal
    Leetcode | Linked List Cycle I && II
    Network | UDP checksum
    Ubuntu下将现有的文件打包成deb包
    Base64编码加密
    requestAnimationFrame 的原理与优势
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9423982.html
Copyright © 2011-2022 走看看