告诉我这段代码GOLANG有什么问题 [英] Tell me what's wrong with this code GOLANG
问题描述
package main
import (
"fmt"
"math"
)
func main() {
distencecalc()
}
func distencecalc() {
fmt.Println("X1 :")
var x1 float64
fmt.Scanf("%f", &x1)
fmt.Print("")
fmt.Println("Y1 :")
var y1 float64
fmt.Scanf("%f", &y1)
fmt.Print("")
fmt.Println("Z1 :")
var z1 float64
fmt.Scanf("%f", &z1)
fmt.Print("")
fmt.Println("X2 :")
var x2 float64
fmt.Scanf("%f", &x2)
fmt.Print("")
fmt.Println("Y2 :")
var y2 float64
fmt.Scanf("%f", &y2)
fmt.Print("")
fmt.Println("Z2 :")
var z2 float64
fmt.Scanf("%f", &z2)
fmt.Print("")
var Xcalc = x2 - x1
var Ycalc = y2 - y1
var Zcalc = z2 - z1
var calcX = math.Pow(Xcalc, 2)
var calcY = math.Pow(Ycalc, 2)
var calcZ = math.Pow(Zcalc, 2)
var allcalc = calcX + calcZ + calcY
fmt.Println("the result is :")
fmt.Println(math.Sqrt(allcalc))
}
问题是我先编译然后运行它询问x1的程序,然后输入值,同时询问y1和z1.
The problem is I compile then run the program it asks about x1 I enter the value and it asks about y1 and z1 at the same time.
推荐答案
实际上,所讨论的代码可在Unix系统上运行,但通常出现的问题是像 fmt.Scanf(%f",& x1)
不使用换行符,而是引用 fmt的软件包文档中的引用:扫描
:
Actually the code in question works on unix systems, but usually the problem is that calls like fmt.Scanf("%f", &x1)
does not consume newlines, but quoting from package doc of fmt: Scanning
:
扫描,Fscan,Sscan将输入中的换行符视为空格.
Scan, Fscan, Sscan treat newlines in the input as spaces.
在Windows上,换行符不是单个 \ n
字符,而是 \ r \ n
,因此后续的 fmt.Scanf()
呼叫将立即进行,而无需等待用户的进一步输入.
And on Windows the newline is not a single \n
character but \r\n
, so the subsequent fmt.Scanf()
call will proceed immediately without waiting for further input from the user.
因此,您必须在格式字符串中添加换行符,以避免随后的 fmt.Scanf()
调用继续进行:
So you have to add a newline to your format string to avoid subsequent fmt.Scanf()
call to proceed:
fmt.Scanf("%f\n", &x1)
但是更容易的是只使用 fmt.Scanln()
并跳过整个格式字符串:
But easier would be to just use fmt.Scanln()
and skip the whole format string:
fmt.Scanln(&x1)
Scanln,Fscanln和Sscanln停止在换行符处进行扫描,并要求在这些项目之后加上换行符或EOF.
Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.
扫描仪函数( fmt.ScanXXX()
)返回成功扫描的项目数和错误
.要确定扫描是否成功,您必须检查其返回值,例如:
The scanner functions (fmt.ScanXXX()
) return you the number of successfully scanned items and an error
. To tell if scanning succeeded, you have to check its return value, e.g.:
if _, err := fmt.Scanln(&x1); err != nil {
fmt.Println("Scanning failed:", err)
}
这篇关于告诉我这段代码GOLANG有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!