dota220141003 2017-09-03 15:00
浏览 66
已采纳

为什么Scanf()无法为我正常工作?

I'm trying to move from Python to GO and with my minimal knowledge I tried to make a basic calculator. However i for some reason can't get Scanf to work properly. It only seems to accept the first scanf but the second one is completely ignored

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?
1: Add
2: Subtract
3: Divide
4: 
    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)
}
  • 写回答

1条回答 默认 最新

  • douke6424 2017-09-03 15:35
    关注

    The second call to Scanf, Scanf("%d", x, y) only provides one conversion specifier but was given two variables.

    Moreover, this second call only passes the variables' values, not their addresses.

    It seems the correct call would be Scanf("%d %d", &x, &y)


    In the first call to Scanf you said: Scanf("%d", &input). The second argument's syntax, & variable, denotes a reference to the named variable.

    input was declared global, but is only visible after its declaration. 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.

    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; in this case, main.

    See Go's documentation for a similar explanation: https://golang.org/ref/spec#Address_operators

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误