为什么 Scanf 的输入始终为 0?

huangapple go评论88阅读模式
英文:

Why the input of Scanf is always 0?

问题

我正在尝试从用户那里获取输入并将其打印出来,但是在我输入一些内容后,距离的值似乎是0

以下是代码:

type Person struct {
    name string
    age int
    ambition string
}

func (p *Person) walking() {
    var distance int
    fmt.Println("输入距离")
    fmt.Scanf("%f", &distance)

    if distance < 9 {
        fmt.Println(p.name, "正在向那个方向行走,距离为", distance,
            "千米")
    } else {
        fmt.Println("这是一个错误,请忽略")
    }
}

func main() {
    p := new(Person)
    p.name = "Joker"

    p.walking()
}

正如你所看到的,无论我在主函数中运行这个命令多少次,它总是打印出fmt.Println(p.name, "正在向那个方向行走,距离为", distance, "千米"),即使距离的值大于9

p.walking() 总是打印出距离为0?有人能解释一下这里发生了什么吗?

英文:

I'm trying to get input from a user and print it out, but apparently the value of the distance is 0, after I did some input.

Here's the code:

type Person struct {
    name string
    age int
    ambition string
}

func (p *Person) walking() {
    var distance int
    fmt.Println(&quot;Enter the distance&quot;)
    fmt.Scanf(&quot;%f&quot;, &amp;distance)

    if distance &lt; 9 {
        fmt.Println(p.name, &quot; is walking towards that direction in &quot;, distance,
            &quot;kilometer&quot;)
    } else {
        fmt.Println(&quot;This is an error, ignore this&quot;)
    }
}

As you can see whenever I try to run this command on my main function, it always prints fmt.Println(p.name, &quot; is walking towards that direction in &quot;, distance, &quot;kilometer&quot;) even though the value of distance is more than 9.

func main() {
    p := new(Person)
    p.name = &quot;Joker&quot;
   
    p.walking()
}

p.walking() will always print distance as 0? Can anyone explain to me what is going on here?

答案1

得分: 5

你使用了错误的格式字符串。%f 用于扫描浮点数,但是你的变量 distance 是整数类型 int,所以你应该使用 %d

fmt.Scanf("%d", &distance)

或者将 distance 变量声明为浮点数类型,然后你可以使用 %f

var distance float64
fmt.Println("Enter the distance")
fmt.Scanf("%f", &distance)

注意:

fmt.Scanf() 返回成功扫描的项目数和一个可选的错误。你应该习惯处理 Go 中的错误,这将节省你很多时间。

最简单的方法是存储和打印 Scanf() 的返回值:

var distance int
fmt.Println("Enter the distance")
n, err := fmt.Scanf("%f", &distance)
fmt.Println(n, err)

输出结果为:

0 bad verb %f for integer

这立即告诉你没有扫描到任何项目,并且出现了错误:bad verb %f for integer,这基本上是自解释的。

这也解释了为什么你总是看到打印出 0 公里:你的 distance 变量被初始化为 0int 的零值),并且从未更改过。

如果扫描成功,你将看到以下输出:

1 <nil>

表示成功扫描了一个项目(即 distance),并且没有错误。

如果你使用一次 Scanf() 扫描多个项目,n 当然可以大于 1(例如 fmt.Scanf("%f %d", &distance, &temp))。

英文:

You used a wrong format string. %f is used to scan floating point numbers, but your variable distance is of type int, so you should use %d:

fmt.Scanf(&quot;%d&quot;, &amp;distance)

Or declare distance variable to be a floating point number and then you can use %f:

var distance float64
fmt.Println(&quot;Enter the distance&quot;)
fmt.Scanf(&quot;%f&quot;, &amp;distance)

Note:

fmt.Scanf() returns the number of items successfully scanned, and an optional error. You should get used to handle errors in Go which would save you a lot of time.

As a minimal by storing and printing the return values of Scanf():

var distance int
fmt.Println(&quot;Enter the distance&quot;)
n, err := fmt.Scanf(&quot;%f&quot;, &amp;distance)
fmt.Println(n, err)

Prints:

0 bad verb %f for integer

Which immediately tells you 0 items were scanned and there was an error: bad verb %f for integer which is pretty much self explanatory.

This also explains why you always see 0 kilomenters printed: your distance variable is initialized to 0 (zero value of int) and it is never changed.

If scanning would be successful, you would see an output of:

1 &lt;nil&gt;

Meaning that one item was scanned successfully (the distance) and there was no error.

If you would scan multiple items with one Scanf() call, n could be greater than 1 of course (for example fmt.Scanf(&quot;%f %d&quot;, &amp;distance, &amp;temp)).

huangapple
  • 本文由 发表于 2015年8月10日 16:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/31914711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定