英文:
Loop prints statement multiple times when entering multiple letters as input - GoLang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是GoLang的新手,遇到了一个问题:如果我输入多个字母作为输入,结果会打印多次。
用户需要输入一个既不是0也不是字母的数字。
如果输入一个字母,变量'num1'将变为'0'(通过打印变量进行检查)。
如果用户输入'0'或字母,他将有另一次机会输入一个数字。
示例:
如果我输入"d",它将正常打印一次。
如果我输入"dd",它将打印两次。
如果我输入"ddd",它将打印三次。
但是,如果我输入"0"或"00",它将正常打印一次。
如何使得无论我输入多少个字母,结果始终只打印一次?
代码:
package main
import "fmt"
func main() {
var num1 float64
for {
fmt.Print("\n第一个数字:")
fmt.Scanln(&num1)
if num1 == 0 {
fmt.Print("无效的输入'第一个数字'")
} else {
break
}
}
fmt.Print("通过")
}
PS:如果可能的话,变量num1应保持为'float64'类型。
谢谢帮助 ^^
英文:
I'm new to GoLang and I have the problem that if I type in multiple letters as a input the outcome will print multiple times.
The user needs to type a number that isn't 0 and isn't letters.
If you type a letter the variable 'num1' will be '0' (checked by printing the variable)
If the user types '0' or letters he will get another try to type in a number.
Example:
If I type "d" it will print once as it should be.
If I type "dd" it will print twice.
If I type "ddd" it will print three times.
But if I type "0" or "00" it will print only once as it should be.
How can I make it so that if I type multiple letters the outcome will always print once?
Code:
package main
import "fmt"
func main() {
var num1 float64
for {
fmt.Print("\nFirst Number: ")
fmt.Scanln(&num1)
if num1 == 0 {
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
PS: The variable num1 should stay as 'float64' if possible
Thanks for the help ^^
答案1
得分: 0
你面临的问题是,当fmt.Scan
无法将字符串转换为浮点数时,未被扫描的部分会保留在缓冲区中。你可以尝试通过实际读取并忽略缓冲区来清除它。
我建议另一种方法是手动解析字符串中的浮点数,像这样:
func main() {
var num1 float64
for {
var input string
var err error
fmt.Print("\nFirst Number: ")
fmt.Scan(&input)
num1, err = strconv.ParseFloat(input, 64)
if err != nil {
fmt.Print("Invalid input for 'First Number'")
}
if num1 == 0 {
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
并且始终确保阅读并理解错误信息。
英文:
The problem you are facing is that the fmt.Scan when fails to convert the string to float, the unscanned bits remain in buffer. You can try to clear the buffur by actually reading and ignoring it.
func main() {
var num1 float64
stdin := bufio.NewReader(os.Stdin)
for {
fmt.Print("\nFirst Number: ")
fmt.Scan(&num1)
if num1 == 0 {
stdin.ReadString('\n')
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
I would recommend another approch my manually parsing the float from string like this:
func main() {
var num1 float64
for {
var input string
var err error
fmt.Print("\nFirst Number: ")
fmt.Scan(&input)
num1, err = strconv.ParseFloat(input, 64)
if err != nil {
fmt.Print("Invalid input for 'First Number'")
}
if num1 == 0 {
fmt.Print("Invalid input for 'First Number'")
} else {
break
}
}
fmt.Print("passed")
}
And always make sure to read the errors and understand them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论