本文介绍了Go中的strconv.Atoi(基本计算器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在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)
}
推荐答案
bufio.Reader.ReadString()
返回直到分隔符为止的数据.因此,您的字符串实际上实际上是"172312 \ n"
. strconv.Atoi()
不喜欢它并返回0.它实际上返回一个错误,但是您可以通过 _
忽略它.
bufio.Reader.ReadString()
returns data up until and including the separator. So your string actually ends up being "172312\n"
. strconv.Atoi()
doesn't like that and returns 0. It actually returns an error but you're ignoring it with _
.
您可以看到此示例:
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")修剪换行符.
.
You can trim the newlines with strings.Trim(number, "\n")
.
这篇关于Go中的strconv.Atoi(基本计算器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!