如何在Go中通过for循环不断将数字加倍?

如何在Go中通过for循环不断将数字加倍?

问题描述:

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 "fmt"

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

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 < 10; i++ {
    fmt.Println(x)
    x *= 2
}

You are using the same variable i to iterate the for loop and to keep doubling. Just use another variable.

package main

import "fmt"

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