【发布时间】:2022-02-24 13:27:02
【问题描述】:
我正在阅读 Caleb Doxsey 的围棋书,我有两个关于 fmt.Scanf http://www.golang-book.com/4 的问题
我想知道为什么程序在第二次 Scanf 之后没有停止并等待用户输入?以及如何测试用户是否输入了整数和/或没有留空?
package main
import (
"fmt"
//"math"
)
// compute square roots by using Newton's method
func main() {
var x float64 //number to take square root
var y float64 //this is the guess
var q float64 //this is the quotient
var a float64 //this is the average
// how do check if the user entered a number
fmt.Print("Enter a number to take its square root: ")
var inputSquare float64
fmt.Scanf("%f", &inputSquare)
// why doesn't program stop after
// the Print statement and wait
// for user input?
fmt.Print("Enter first guess ")
var inputGuess float64
fmt.Scanf("%f", &inputGuess)
//x = 2
x = inputSquare
y = inputGuess
for i := 0; i < 10; i++ { //set up the for loop for iterations
q = x/y //compute the quotient; x and y are given
a = (q + y) / x //compute the average
y = a //set the guess to the average
} //for the next loop
fmt.Println("y --> ", y)
//fmt.Println("Sqrt(2)", math.Sqrt(2))
}
【问题讨论】:
-
它适合我。我猜这是一个行尾问题。如果你在 Windows 上运行,行尾通常用 '\r\n' 表示,而在 Mac OS X 和 Linux(我测试过的地方)上,它只是 '\n'。我的猜测是 Go 可能正在读取 '\r' ,将其视为行尾,并将 '\n' 留在流中。所以当你再次调用 fmt.Scanf 时,缓冲区中已经有东西了,不需要阻塞。不过,这只是一个疯狂的猜测。
-
好的。任何建议如何解决它?这就是我在 Windows 命令行中运行的内容: c:\Go\src\play\exercise>go run loop_exercise.go 输入一个数字来取其平方根: 2 Enter first guess y --> +Inf
-
如果您使用 Scanf 调用显式读取换行符会发生什么?喜欢“
fmt.Scanf("%f\n", &inputGuess)”?或者,您可以在每次读取后刷新标准输入。我不知道去哪里告诉你去哪里找一个 Flush 函数。 -
是的,添加
\n解决了这个问题。
标签: go