执行:使用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!
我有以下代码: p>
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)
code > pre>
在最后一个打印语句中,如果我打印 string1 code>,它将返回正确的值,但是如果我尝试打印 string2 code>,则返回正确的值 无论输入到控制台的值是什么,都将返回0。 p>
有人知道为什么会这样吗?
谢谢! p>
div>
答
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)
}