这是发行5391:
fmt:
Scanf拒绝
rn在Windows上线的末端。
作为一种解决方法,要检查输入是否有效,请编写,
var inputSquare float64n, err := fmt.Scanf("%fn", &inputSquare)if err != nil || n != 1 { // handle invalid input fmt.Println(n, err)}和
var inputGuess float64n, err = fmt.Scanf("%fn", &inputGuess)if err != nil || n != 1 { // handle invalid input fmt.Println(n, err)}解决方法是
"%fn"格式字符串中的换行符。
包
fmt功能扫描
func Scanf(format string, a ...interface{}) (n int, err error)Scanf扫描从标准输入读取的文本,将连续的以空格分隔的值存储到由格式确定的连续的参数中。它返回成功扫描的项目数。
这是一个完整的工作程序:
package mainimport ( "fmt")// compute square roots by using Newton's methodfunc 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 fmt.Print("Enter a number to take its square root: ") var inputSquare float64 n, err := fmt.Scanf("%fn", &inputSquare) if err != nil || n != 1 { // handle invalid input fmt.Println(n, err) return } fmt.Print("Enter first guess ") var inputGuess float64 n, err = fmt.Scanf("%fn", &inputGuess) if err != nil || n != 1 { // handle invalid input fmt.Println(n, err) return } x = inputSquare y = inputGuess for i := 0; i < 10; i++ { 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 } fmt.Printf("sqrt(%g) = %gn", x, y)}输出:
Enter a number to take its square root: 2.0Enter first guess 1.0sqrt(2) = 1.414213562373095
我在Windows 7上使用Go 1.1.1:
C:>go versiongo version go1.1.1 windows/amd64



