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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)