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

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

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 (
    &quot;fmt&quot;
    &quot;os&quot;
    &quot;strconv&quot;
)

var numbers []float64
var sum float64 = 0

func main() {

    if len(os.Args) &lt;= 1 {
        return
    }

    for _, arg := range os.Args[1:] {
        if n, err := strconv.ParseFloat(arg, 64); err == nil {
            numbers = append(numbers, n)
        }
    }

    fmt.Println(&quot;Numbers are: &quot;, numbers)
    for _, value := range numbers {
        sum += value
    }

}

答案2

得分: 2

无法转换,因为stringint不兼容。

不需要使用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(&quot;Numbers are: &quot;)
for _, arg := range os.Args[1:] {
    fmt.Print(arg, &quot; &quot;)
    value, err := strconv.ParseFloat(arg, 64)
    if err != nil {
        panic(err)
    }
    sum += value
}

huangapple
  • 本文由 发表于 2015年1月10日 19:02:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/27875479.html
匿名

发表评论

匿名网友

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

确定