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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里