duanji2002 2016-04-03 15:35
浏览 75
已采纳

执行:使用strconv.String转换字符串为float返回0

I have the following code:

reader := bufio.NewReader(os.Stdin)
fmt.Print("room: width x length: ")

inStr, _ := reader.ReadString('
')
result := strings.Split(inStr, "x")

string1, _ := strconv.ParseFloat(result[0], 64)
string2, _ := strconv.ParseFloat(result[1], 64)
fmt.Print(string2)

At the last print statement, if i print string1 it returns the right value, but if i try to print string2 it returns 0, no matter what value i input to the console.

Does anyone know why this is happening? Thanks!

  • 写回答

1条回答 默认 最新

  • doucan8276 2016-04-03 15:39
    关注

    Replace

    result := strings.Split(inStr, "x")
    

    with

    result := strings.Split(strings.TrimSpace(inStr), "x")
    

    As string contains so your second array element contains it too.

    Also I really suggest to look at error messages before posting such kind of questions. You could see strconv.ParseFloat: parsing "23 ": invalid syntax as result of next code

    string2, err := strconv.ParseFloat(result[1], 64)
    if err != nil {
        fmt.Println(e)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效