【问题标题】:strconv.Atoi in Go (Basic calculator)Go 中的 strconv.Atoi(基本计算器)
【发布时间】:2018-04-16 20:22:59
【问题描述】:

我正在尝试在 Go 中制作一个基本的加法计算器(在这里完成新手),但每次我得到的输出都是 0。

这是代码:

package main

import (
    "fmt"
    "strconv"
    //"flag"
    "bufio"
    "os"
)

func main(){
     reader := bufio.NewReader(os.Stdin)
     fmt.Print("What's the first number you want to add?: ")
     firstnumber, _ := reader.ReadString('\n')
     fmt.Print("What's the second number you want to add?: ")
     secondnumber, _ := reader.ReadString('\n')
     ifirstnumber, _ := strconv.Atoi(firstnumber)
     isecondnumber, _ := strconv.Atoi(secondnumber)
     total := ifirstnumber + isecondnumber
     fmt.Println(total)

}

【问题讨论】:

    标签: go calculator strconv


    【解决方案1】:

    bufio.Reader.ReadString() 返回数据直到并包括分隔符。所以你的字符串实际上最终是"172312\n"strconv.Atoi() 不喜欢这样并返回 0。它实际上返回了一个错误,但你用 _ 忽略了它。

    你可以看到this example会发生什么:

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main(){
         ifirstnumber, err := strconv.Atoi("1337\n")
         isecondnumber, _ := strconv.Atoi("1337")
         fmt.Println(err)
         fmt.Println(ifirstnumber, isecondnumber)
    }
    

    您可以使用strings.Trim(number, "\n") 修剪换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多