Go语言之旅练习 #2: For循环的继续

huangapple go评论83阅读模式
英文:

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 &quot;fmt&quot;

func main() {
    sum := 1
    for ; sum &lt; 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 &lt; x) {
    sum = sum * 2
}

huangapple
  • 本文由 发表于 2015年11月29日 12:25:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/33979399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定