英文:
How to convert []string to []float64 in Golang?
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是编程新手,正在尝试用Go语言编写一个简单的平均数程序。
package main
import (
"fmt"
"os"
)
var numbers []float64
var sum float64 = 0
func main() {
if len(os.Args) > 1 {
numbers = os.Args[1:]
}
fmt.Println("Numbers are: ", numbers)
for _, value := range numbers {
sum += value
}
}
当我构建程序时,出现了以下错误:
prog.go:15: cannot use os.Args[1:] (type []string) as type []float64 in assignment
[process exited with non-zero status]
那么如何将字符串切片转换为浮点数切片?我可以将转换函数映射到切片中吗?
英文:
I'm new to programming, and trying to write a simple average program in Go.
package main
import (
"fmt"
"os"
)
var numbers []float64
var sum float64 = 0
func main() {
if len(os.Args) > 1 {
numbers = os.Args[1:]
}
fmt.Println("Numbers are: ", numbers)
for _, value := range numbers {
sum += value
}
}
http://play.golang.org/p/TWNltPO71N
when I build the program, I got this error:
prog.go:15: cannot use os.Args[1:] (type []string) as type []float64 in assignment
[process exited with non-zero status]
So how to convert a slice of string to a slice of float numbers? Can I map a convert function to the slice?
答案1
得分: 10
你需要使用strconv.ParseFloat
函数将字符串转换为float64
类型:
package main
import (
"fmt"
"os"
"strconv"
)
var numbers []float64
var sum float64 = 0
func main() {
if len(os.Args) <= 1 {
return
}
for _, arg := range os.Args[1:] {
if n, err := strconv.ParseFloat(arg, 64); err == nil {
numbers = append(numbers, n)
}
}
fmt.Println("Numbers are: ", numbers)
for _, value := range numbers {
sum += value
}
}
英文:
You need to convert string to float64 using strconv.ParseFloat function:
package main
import (
"fmt"
"os"
"strconv"
)
var numbers []float64
var sum float64 = 0
func main() {
if len(os.Args) <= 1 {
return
}
for _, arg := range os.Args[1:] {
if n, err := strconv.ParseFloat(arg, 64); err == nil {
numbers = append(numbers, n)
}
}
fmt.Println("Numbers are: ", numbers)
for _, value := range numbers {
sum += value
}
}
答案2
得分: 2
无法转换,因为string
和int
不兼容。
不需要使用numbers
切片,只需遍历os.Args[1:]
,并使用strconv
包中的ParseFloat函数。
fmt.Print("Numbers are: ")
for _, arg := range os.Args[1:] {
fmt.Print(arg, " ")
value, err := strconv.ParseFloat(arg, 64)
if err != nil {
panic(err)
}
sum += value
}
英文:
It can't convert because string
and int
are not compatible.
Instead of having the numbers
slice, just iterate over os.Args[1:]
, using ParseFloat from the strconv
package.
fmt.Print("Numbers are: ")
for _, arg := range os.Args[1:] {
fmt.Print(arg, " ")
value, err := strconv.ParseFloat(arg, 64)
if err != nil {
panic(err)
}
sum += value
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论