英文:
Tour of Go exercise #2: For continued
问题
这可能是我无法理解的一个简单问题,但我正在进行Go Tour的学习,在For continued
部分,我想知道有人能否解释一下逻辑是如何执行并得出1024
这个结果的。
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
}
链接:https://tour.golang.org/flowcontrol/2
英文:
This may be a simple thing I can't see for some reason but I am going through the Go Tour and in the For continued
section and I was wondering if someone could explain to me how the logic executes and delivers the statement to be 1024
.
https://tour.golang.org/flowcontrol/2
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
}
答案1
得分: 4
这实际上只是计算2的幂次方。
所以输出结果是:
1 2 4 8 16 32 ... 1024
可以将这个循环理解为:
sum = 1
while(sum < x) {
sum = sum * 2
}
英文:
Its really just doing powers of 2
so the outputs are
1 2 4 8 16 32 ... 1024
Think of this loop as
sum = 1
while(sum < x) {
sum = sum * 2
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论