dongzhi4470 2016-08-04 21:48
浏览 1791
已采纳

使用Golang中的ParseFloat将字符串输入转换为float64

I've just started learning Go and I'm trying to convert a string from standard input to a float64 so I can perform an arithmetic operation on the input value.

The output returns "0 feet converted to meters gives you 0 meters" regardless of the input value. I can't figure out why the value is zero after invoking ParseFloat on the input.

If someone could please point out to me why this is happening, I would greatly appreciate it.

const conversion float64 = 0.3048

func feetToMeters (feet float64) (meters float64) {
  return feet * conversion
}

func main(){
  fmt.Println("

This program will convert feet to meters for you!
")

  reader := bufio.NewReader(os.Stdin)
  fmt.Println("Enter feet value: 
")
  feet, _ := reader.ReadString('
')

  feetFloat, _ := strconv.ParseFloat(feet, 64)

  meters := feetToMeters(feetFloat)

  fmt.Printf("%v feet converted to meters give you %v meters",feetFloat,meters)
}
  • 写回答

1条回答 默认 最新

  • duanjing7459 2016-08-04 22:08
    关注

    The problem is that you try to parse "x.x ", e.g: 1.8 . And this returns an error: strconv.ParseFloat: parsing "1.8 ": invalid syntax. You can do a strings.TrimSpace function or to convert feet[:len(feet)-1] to delete character

    With strings.TrimSpace() (you need to import strings package):

    feetFloat, _ := strconv.ParseFloat(strings.TrimSpace(feet), 64)
    

    Wtih feet[:len(feet)-1]:

    feetFloat, _ := strconv.ParseFloat(feet[:len(feet)-1], 64)
    

    Output in both cases:

    10.8 feet converted to meters give you 3.2918400000000005 meters
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义