猿问

为什么这是以下代码的输出?

我无法理解为什么此代码的输出为 16。如果我的格式有误,我深表歉意,我是编码新手。


我已经写了几次代码以确保我的格式正确


x = 1

while x < 10:

    x += x

print(x)

为我打印的输出是 16。


慕雪6442864
浏览 148回答 2
2回答

尚方宝剑之说

对于我,这说得通。该语句x += x相当于x *= 2,加倍x。为了帮助您理解,请x在每次迭代后尝试打印:x = 1while x < 10:&nbsp; &nbsp; x += x&nbsp; &nbsp; print(x)输出:24816在每一步:2&nbsp; &nbsp; # greater than 10? no4&nbsp; &nbsp; # greater than 10? no8&nbsp; &nbsp; # greater than 10? no16&nbsp; &nbsp;# greater than 10? yes, stop loop

沧海一幻觉

也许更改 的位置print(x)可以帮助您:x = 1print(1)while x < 10:&nbsp; &nbsp; x += x&nbsp; &nbsp; print(x)输出:124816如您所见,有一个共同的赞助人。每次迭代都会while复制之前的值x(这是由于x += x,可以解释为 x 的两倍)。那么,条件while x < 10就很简单了。1&nbsp; &nbsp; &nbsp;# Less than 10. Keep looping.2&nbsp; &nbsp; &nbsp;# Less than 10. Keep looping.4&nbsp; &nbsp; &nbsp;# Less than 10. Keep looping.8&nbsp; &nbsp; &nbsp;# Less than 10. Keep looping.16&nbsp; &nbsp; # Greater than 10. STOP!
随时随地看视频慕课网APP

相关分类

Python
我要回答