Pie*_*Pah -6 arrays for-loop go
为什么这个函数打印出一个[83 83 83 83 83]而不是[98 93 77 82 83]?
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)
}
Run Code Online (Sandbox Code Playgroud)
因为你正在填充x[i]每个值scores.
你有一个额外的循环.
由于切片的最后一个值为scores83,因此您将x再次填充一次,每个插槽为83.
更简单的是:
for i, _ := range x {
// fill up x array with elements of scores array
x[i] = scores[i]
}
Run Code Online (Sandbox Code Playgroud)
输出: [98 93 77 82 83]