krahets / hello-algo

《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 代码。简体版和繁体版同步更新,English version ongoing
https://www.hello-algo.com
Other
95.04k stars 12.07k forks source link

描述示例有歧义 #1433

Closed pyj1971341376 closed 1 month ago

pyj1971341376 commented 2 months ago

while 循环比 for 循环的自由度更高。在 while 循环中,我们可以自由地设计条件变量的初始化和更新步骤。

例如在以下代码中,条件变量 。每轮进行两次更新,这种情况就不太方便用 for 循环实现:

i每轮进行值的双倍更新,用for循环不是更规范直接嘛?while确实灵活度更高,但是举一个条件变化更为灵活的示例是不是更好一些呢,也更有助于初学者进行理解使用

studyingegret commented 2 months ago

请问你指的是哪一页哪里的文字?方便我也看看(发个URL)

krahets commented 2 months ago

Hi,书中的示例对 i 进行了“两次更新”而非仅“双倍更新”,即:

while i <= n:
    res += i
    # 更新条件变量
    i += 1
    i *= 2

我们还可以对示例稍作拓展,更加体现 while 的灵活性:

while i <= n:
    i += 1
    res += i
    i *= 2
    res *= i