dsyct08008 2017-05-20 22:19
浏览 93
已采纳

在Go中将英尺和英寸转换为厘米?

I am new to Go and I am a bit stuck on a problem regarding human height conversion from feet/inches to cm.

How can I convert, in an efficient way, a string that looks like this 5'2'' to an centimeter int?

Edit: After some more testing I ended up with this solution. How can it be improved?

height := strings.Split("5'2''", "'")
heightfeet,err :=strconv.ParseFloat(height[0],10)
heightinch,err :=strconv.ParseFloat(height[1],10)
heightcm :=heightfeet*30.48+heightinch*2.54
  • 写回答

1条回答 默认 最新

  • douchuanchai2793 2017-05-20 23:02
    关注

    I feel like your approach is fine, but, if you actually want to be sure to extract only the integers and using constants take a look at this Go Playground I set up.

    package main
    
    import (
        "fmt"
        "regexp"
        "strconv"
    )
    
    func main() {
    
        //Defining our constants     
        const cm1 = 30.48       
        const cm2 =  2.54 
    
        //Slice to contain parsed ints
        var parsedTokens []float64
    
        feet := "5'2''"
    
        //Regex to extract only integers
        reg := regexp.MustCompile("[0-9]+")
        filtered:= reg.FindAllString(feet, -1)
    
        //Parse each value v in filtered and append it into parsedTokens
        for _, v := range filtered {
            k, _ := strconv.ParseFloat(v, 64)
            parsedTokens = append(parsedTokens, k)
        }
    
        //157.48000000000002
        fmt.Println(parsedTokens[0]*cm1 + parsedTokens[1]*cm2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题