2014-09-24 35 views
-6

爲什麼此函數會打印出[83 83 83 83 83]而不是[98 93 77 82 83]Go中的嵌套循環陣列行爲不像其他語言的陣列

package main 

import "fmt" 

func main() { 
    var x [5]float64 
    scores := [5]float64{ 98, 93, 77, 82, 83, } 

    for i, _ := range x { 
     for j, _ := range scores { 
      // fill up x array with elements of scores array 
      x[i] = scores[j] 
     } 
    } 
    fmt.Println(x) 
} 

回答

5

因爲你是填充x[i]與每個scores值的。
你有一個額外的循環。

由於片段scores的最後一個值爲83,因此您將再次填充x,每個插槽的值爲83。

簡單的將是:

for i, _ := range x { 
    // fill up x array with elements of scores array 
    x[i] = scores[i] 
} 

play.golang.org

輸出:[98 93 77 82 83]

+0

該劇的鏈接似乎是世界你好。 – ams 2014-09-24 13:39:28

+1

@ams我已修復play.golang.org鏈接 – VonC 2014-09-24 13:41:55

+0

謝謝你的明確答案。 – PieOhPah 2014-11-30 22:08:13

1

你有太多的循環。寫:

package main 

import "fmt" 

func main() { 
    var x [5]float64 
    scores := [5]float64{98, 93, 77, 82, 83} 
    for i := range x { 
     x[i] = scores[i] 
    } 
    fmt.Println(x) 
} 

輸出:

[98 93 77 82 83] 

在這種情況下,你可以簡單地寫:

package main 

import "fmt" 

func main() { 
    var x [5]float64 
    scores := [5]float64{98, 93, 77, 82, 83} 
    x = scores 
    fmt.Println(x) 
} 

輸出:

[98 93 77 82 83]