douyi8315
2014-09-24 11:30
浏览 34
已采纳

Go中的嵌套循环数组与其他语言的数组不一样

Why is this function printing out an array of [83 83 83 83 83] instead of [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)
}

图片转代码服务由CSDN问答提供 功能建议

为什么此函数打印出 [83 83 83 83 83] 数组 的 [98 93 77 82 83] 吗?

 包main 
 
import“ fmt” 
 
func main(){
 var  x [5] float64 
分数:= [5] float64 {98,93,77,82,83,} 
 
对于i,_:=范围x {
对于j,_:=范围分数{  
 //用分数数组元素填充x数组
x [i] =分数[j] 
} 
} 
 fmt.Println(x)
} 
    
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyao2129 2014-09-24 11:55
    已采纳

    Because you are filling x[i] with each of the values of scores.
    You have one extra loop.

    Since the last value of the slice scores is 83, you are filling x one more time, with 83 for each slot.

    Simpler would be:

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

    play.golang.org

    Output: [98 93 77 82 83]

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douyong5476 2014-09-24 12:44

    You have too many loops. Write:

    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)
    }
    

    Output:

    [98 93 77 82 83]
    

    In this case, you could simply write:

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

    Output:

    [98 93 77 82 83]
    
    评论
    解决 无用
    打赏 举报