2017-11-04 11 views
0

私はゴーでの基本的な足し算計算(ここでは完全にnoobのを)作るしようとしているが、私はすべての時間が0strconv.Atoi(基本電卓)

これの出力を取得

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) 

} 

答えて

4

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")で改行をトリミングすることができます。

関連する問題