[英]Why doesn't Scanf() work correctly for me?
I'm trying to move from Python to GO and with my minimal knowledge I tried to make a basic calculator. 我正尝试从Python转到GO,并以我的最少知识尝试制作一个基本的计算器。 However i for some reason can't get Scanf to work properly.
但是我由于某种原因无法使Scanf正常工作。 It only seems to accept the first scanf but the second one is completely ignored
它似乎只接受第一个scanf,但是第二个被完全忽略
package main
import (
"fmt"
)
var x int
var y int
var result int
var input float64
func add(x int, y int) int {
sum := x + y
return sum
}
func sub(x int, y int) int {
sum := x - y
return sum
}
func div(x int, y int) int {
sum := x / y
return sum
}
func mul(x int, y int) int {
sum := x * y
return sum
}
func main() {
fmt.Println("Which type?\n1: Add\n2: Subtract\n3: Divide\n4:
Multiply")
fmt.Scanf("%d", &input)
fmt.Println("Input numbers seperated by space")
fmt.Scanf("%d", x, y)
switch input {
case 1:
result = add(x, y)
case 2:
result = sub(x, y)
case 3:
result = div(x, y)
case 4:
result = mul(x, y)
}
fmt.Println(result)
}
The second call to Scanf, Scanf("%d", x, y)
only provides one conversion specifier but was given two variables. 对Scanf的第二次调用
Scanf("%d", x, y)
仅提供一个转换说明符,但提供了两个变量。
Moreover, this second call only passes the variables' values, not their addresses. 而且,第二次调用仅传递变量的值, 而不传递变量的地址。
It seems the correct call would be Scanf("%d %d", &x, &y)
似乎正确的调用应该是
Scanf("%d %d", &x, &y)
In the first call to Scanf you said: Scanf("%d", &input)
. 在第一次致电Scanf时,您说过:
Scanf("%d", &input)
。 The second argument's syntax, & variable
, denotes a reference to the named variable. 第二个参数的语法
& variable
表示对命名变量的引用 。
input
was declared global, but is only visible after its declaration. input
已声明为全局,但仅在声明后可见。 Since input
is in scope within main
but not within Scanf
, in order for Scanf
to change the value in another scope, the address must be given as an argument, rather than its value. 由于
input
在main
范围内, 而不在Scanf
范围内,为了使Scanf
可以在另一个范围内更改值,因此必须将地址作为参数而不是其值。
The recipient of the address (here Scanf
) can then change the value of the variable in the frame in which it is still in scope; 然后,地址的接收者(在此为
Scanf
)可以在仍处于作用域的框架中更改变量的值; in this case, main
. 在这种情况下,
main
。
See Go's documentation for a similar explanation: https://golang.org/ref/spec#Address_operators 有关类似的说明,请参见Go的文档: https : //golang.org/ref/spec#Address_operators
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.