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

huangapple go评论71阅读模式
英文:

How to square all the number in my array? Golang

问题

package main

import (
	"fmt"
)

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

	square = box[0] * box[0]

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

有人可以告诉我正确的求平方的方法吗?
问题是无效的直接求平方方式(类型为[4]int)。

英文:
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)
}

Anyone can tell me the correct way to square it?
The problem is invalid direct of square(type[4]int)

答案1

得分: 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("第一个盒子的平方是", square)
}

这段代码创建了一个名为box的切片,其中包含了一些整数。然后,它创建了一个与box切片相同长度的切片square。接下来,通过遍历box切片中的元素,将每个元素的平方存储到square切片中。最后,使用fmt.Println函数打印出square切片中第一个元素的平方值。

英文:

You probably want something like this:

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

huangapple
  • 本文由 发表于 2014年11月24日 22:55:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/27107674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定