gpt4 book ai didi

for-loop - 如果有 scanf,为什么循环时会得到重复的输出?

转载 作者:行者123 更新时间:2023-12-03 03:15:44 25 4
gpt4 key购买 nike

当用户输入错误的数字时,代码期望显示一次输出消息,但这是重复的。为什么?

注意:似乎是循环内的 scanf 的问题,因为如果我单独使用 scan,它会按预期工作。

无论如何,我不明白为什么会有这种行为

package main

import (
"fmt"
"math/rand"
"time"
)

func main(){
rand.Seed(time.Now().UnixNano())

var number int = rand.Intn(99)
var input int = 0

fmt.Println("random: ", number)

fmt.Println("enter a number: ")
fmt.Scanf("%d",&input)

for {
if number != input {
fmt.Println("wrong! try again:")
fmt.Scanf("%d",&input)
continue
} else {
fmt.Println("that's correct!")
break
}
}
}

最佳答案

要适应 Windows,请编写 fmt.Scanf("%d\n", &input):

package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
rand.Seed(time.Now().UnixNano())

var number int = rand.Intn(99)
var input int = 0

fmt.Println("random: ", number)

fmt.Println("enter a number: ")
fmt.Scanf("%d\n", &input)

for {
if number != input {
fmt.Println("wrong! try again:")
fmt.Scanf("%d\n", &input)
continue
} else {
fmt.Println("that's correct!")
break
}
}
}

输出:

random:  84
enter a number:
42
wrong! try again:
42
wrong! try again:
84
that's correct!
<小时/>

Windows 使用 "\r\n" 作为行尾。 Linux 和其他操作系统使用 "\n" 表示行尾。

您没有检查 Scanf 错误。

package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
rand.Seed(time.Now().UnixNano())

var number int = rand.Intn(99)
var input int = 0

fmt.Println("random: ", number)

fmt.Println("enter a number: ")
n, err := fmt.Scanf("%d", &input)
if err != nil {
fmt.Println(n, err)
}

for {
if number != input {
fmt.Println("wrong! try again:")
n, err := fmt.Scanf("%d", &input)
if err != nil {
fmt.Println(n, err)
}
continue
} else {
fmt.Println("that's correct!")
break
}
}
}

输出(Windows):

random:  84
enter a number:
42
wrong! try again:
0 unexpected newline
wrong! try again:
42
wrong! try again:
0 unexpected newline
wrong! try again:
84
that's correct!

Windows 将 “42\r\n” 扫描为 “42\r”“\n”

输出(Linux):

random:  84
enter a number:
42
wrong! try again:
42
wrong! try again:
84
that's correct!

Linux 扫描“42\n”

关于for-loop - 如果有 scanf,为什么循环时会得到重复的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com