简体   繁体   English

如何在Golang中将[]字符串转换为[] float64?

[英]How to convert []string to []float64 in Golang?

I'm new to programming, and trying to write a simple average program in Go. 我是编程的新手,并试图在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 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? 我可以将转换函数映射到切片吗?

You need to convert string to float64 using strconv.ParseFloat function: 您需要使用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
    }

}

It can't convert because string and int are not compatible. 它无法转换,因为stringint不兼容。

Instead of having the numbers slice, just iterate over os.Args[1:] , using ParseFloat from the strconv package. 代替具有的numbers片,只是遍历os.Args[1:] ,使用ParseFloatstrconv包。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM