如何在 Golang 中将 []string 转换为 []float64?

我是编程新手,并试图用 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


当我构建程序时,出现此错误:


prog.go:15: cannot use os.Args[1:] (type []string) as type []float64 in assignment

[process exited with non-zero status]

那么如何将一段字符串转换为一段浮点数呢?我可以将转换函数映射到切片吗?


白衣非少年
浏览 841回答 2
2回答

精慕HU

您需要使用strconv.ParseFloat函数将字符串转换为 float64 :package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strconv")var numbers []float64var sum float64 = 0func main() {&nbsp; &nbsp; if len(os.Args) <= 1 {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; for _, arg := range os.Args[1:] {&nbsp; &nbsp; &nbsp; &nbsp; if n, err := strconv.ParseFloat(arg, 64); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numbers = append(numbers, n)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("Numbers are: ", numbers)&nbsp; &nbsp; for _, value := range numbers {&nbsp; &nbsp; &nbsp; &nbsp; sum += value&nbsp; &nbsp; }}

跃然一笑

它无法转换,因为string和int不兼容。相反,具有的numbers片,只是迭代os.Args[1:],使用ParseFloat从strconv包。fmt.Print("Numbers are: ")for _, arg := range os.Args[1:] {&nbsp; &nbsp; fmt.Print(arg, " ")&nbsp; &nbsp; value, err := strconv.ParseFloat(arg, 64)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; sum += value}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go