How do I keep doubling a number through a for loop in Go?

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

How do I keep doubling a number through a for loop in Go?

问题

我已经尝试了许多不同的方法,但都没有成功。这是一个简单的问题,但我一直在努力解决,找不到很多有用的资源。

以下是我尝试过的部分代码:

package main

import "fmt"

func main() {
    for i := 1; i < 10; i++ {
        i := (i * 2)
        fmt.Println(i)
    }
}
英文:

I've tried many different things, to no avail. This is a simple thing but I'm struggling with it, and can't find much helpful resources.

Here's part of what I have tried:

package main

import &quot;fmt&quot;

func main() {
	for i := 1; i &lt; 10; i++ {
		i := (i * 2)
		fmt.Println(i)
	}
}

答案1

得分: 3

你正在将 i 值加倍,但是你在每次迭代中都创建了一个新的 i,其值来自于 for 循环语句中使用的 i

你可能想要像这样的代码:

x := 1
for i := 1; i < 10; i++ {
	fmt.Println(x)
	x *= 2
}
英文:

You are doubling i, but you're creating a new i every iteration, with with the value from the i used in the for loop clause.

You probably want something like

x := 1
for i := 1; i &lt; 10; i++ {
	fmt.Println(x)
	x *= 2
}

huangapple
  • 本文由 发表于 2017年6月14日 06:05:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44532365.html
匿名

发表评论

匿名网友

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

确定