在我下面的代码中,当用户正确地浮动时,它可以正常工作。但是,当他们输入一些随机字符串时,它会打印错误消息并再次提示每个字符。这是为什么?
package main
import "fmt"
func readFloat(title string) float64 {
var userInput float64
for {
fmt.Println("Please enter a float: ")
_, err := fmt.Scanf("%f", &userInput)
if err != nil {
fmt.Printf("Wooops! That's not a float\n")
} else {
return userInput
}
}
}
func main() {
var f float64
f = readFloat("acceleration")
fmt.Printf("You entered: %.04f\n", f)
}
~/src/coursera/go/course-2-functions-methods/week2 $ go run so.go
Please enter a float:
33.3
You entered: 33.3000
~/src/coursera/go/course-2-functions-methods/week2 $ go run so.go
Please enter a float:
sdf
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float:
Wooops! That's not a float
Please enter a float:
慕无忌1623718
一只斗牛犬
相关分类