drbvm26000
drbvm26000
2018-12-20 15:54

将float64数组转换为float32数组

  • type-conversion
  • arrays
已采纳

I have an array of float64 and want to convert each value to float32.

I've tried:

# What I have 
features64 [120]float64

# What I've tried
features32 = [120]float32(features64)

But that gives the compile error:

cannot convert features (type [120]float64) to type [120]float32

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douxianji6181 douxianji6181 3年前

    For example,

    package main
    
    func main() {
        var features64 [120]float64
    
        var features32 [len(features64)]float32
        for i, f64 := range features64 {
            features32[i] = float32(f64)
        }
    }
    
    点赞 评论 复制链接分享
  • dtrotfd1012 dtrotfd1012 3年前

    Simply

    var arr1 [120]float64
    var arr2 [120]float32
    for i, v := range arr1 {
        arr2[i] = float32(v)
    }
    
    点赞 评论 复制链接分享
  • dongqi6964 dongqi6964 3年前

    You can't convert one slice/array type to another. You'll need to create a new array and iterate over the original converting each element:

    for i,f := range features64 {
        features32[i] = float32(f)
    }
    
    点赞 评论 复制链接分享

为你推荐