如何平方数组中的所有数字? Golang

时间:2014-11-24 14:55:49

标签: go

package main

import (
    "fmt"
)

func main() {
    var square int
    box := [4]int{1, -2, 3, 4}

    square = box * *box

    fmt.Println("The square of the first box is", square)
}

任何人都可以告诉我正确的方法吗? 问题是square的直接无效(type [4] int)

1 个答案:

答案 0 :(得分:8)

你可能想要这样的东西:

package main

import (
  "fmt"
)

func main() {
  box := []int{1, -2, 3, 4}
  square := make([]int, len(box))
  for i, v := range box {
    square[i] = v*v
  }

  fmt.Println("The square of the first box is ", square)
}