Convert feet and inches to centimeters in Go?

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

Convert feet and inches to centimeters in Go?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,对于将人的身高从英尺/英寸转换为厘米的问题有些困惑。

我应该如何高效地将一个看起来像5'2''的字符串转换为整数表示的厘米?

编辑:
经过一些测试,我得到了以下解决方案。如何改进它?

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
英文:

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

得分: 2

我觉得你的方法还不错,但是如果你确实想要确保只提取整数并使用常量,可以参考我设置的这个Go Playground

package main

import (
	"fmt"
	"regexp"
	"strconv"
)

func main() {
   
    //定义常量     
    const cm1 = 30.48       
    const cm2 =  2.54 

    //用于存储解析后的整数的切片
	var parsedTokens []float64

	feet := "5'2''"
    
    //用正则表达式提取整数
	reg := regexp.MustCompile("[0-9]+")
	filtered:= reg.FindAllString(feet, -1)
	
    //解析每个值v并将其追加到parsedTokens中
	for _, v := range filtered {
		k, _ := strconv.ParseFloat(v, 64)
		parsedTokens = append(parsedTokens, k)
	}
	
    //157.48000000000002
	fmt.Println(parsedTokens[0]*cm1 + parsedTokens[1]*cm2)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2017年5月21日 06:19:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/44091338.html
匿名

发表评论

匿名网友

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

确定