For loop 为什么以下代码的输出在GO语言中是错误的
这是我为实现堆栈而编写的代码。当我执行这个时,它会生成一些完全不同的输出。附加了输出的屏幕截图。为什么程序会产生如此无效的输出?代码中有错误吗For loop 为什么以下代码的输出在GO语言中是错误的,for-loop,go,stack,scanf,For Loop,Go,Stack,Scanf,这是我为实现堆栈而编写的代码。当我执行这个时,它会生成一些完全不同的输出。附加了输出的屏幕截图。为什么程序会产生如此无效的输出?代码中有错误吗 package main import "fmt" var st [100]int var top int func main() { top = -1 ch := 0 temp := 0 for true { fmt.Println("Enter you choice:") fmt.
package main
import "fmt"
var st [100]int
var top int
func main() {
top = -1
ch := 0
temp := 0
for true {
fmt.Println("Enter you choice:")
fmt.Println("1. PUSH\n2. POP\n3. PRINT\n4. EXIT")
fmt.Scanf("%d", &ch)
switch ch {
case 1:
fmt.Println("Enter the value...")
fmt.Scanf("%d", &temp)
push(temp)
case 2:
temp = pop()
if temp != -1 {
fmt.Println("The popped value is ", temp)
}
case 3:
print()
case 4:
break
default:
fmt.Println("Please enter a valid choice")
}
}
}
func print() {
i := 0
if top == -1 {
fmt.Println("First insert elements into the stack")
} else {
fmt.Printf("The values are as follows")
for i <= top {
fmt.Println(st[i])
i++
}
}
}
func pop() int {
if top == -1 {
fmt.Println("Please push values before popping")
return -1
}
temp := st[top]
top--
return temp
}
func push(n int) {
top++
st[top] = n
}
主程序包
输入“fmt”
var st[100]int
var top int
func main(){
top=-1
ch:=0
温度:=0
真的{
fmt.Println(“输入您的选择:”)
fmt.Println(“1.推送\n2.弹出\n3.打印\n4.退出”)
格式扫描(“%d”和“ch”)
开关ch{
案例1:
fmt.Println(“输入值…”)
模板扫描(“%d”和“临时”)
推送(温度)
案例2:
temp=pop()
如果温度!=-1{
fmt.Println(“弹出的值为”,temp)
}
案例3:
打印()
案例4:
打破
违约:
fmt.Println(“请输入有效选项”)
}
}
}
func print(){
i:=0
如果top==-1{
fmt.Println(“首次将元素插入堆栈”)
}否则{
fmt.Printf(“值如下所示”)
对于i而言,问题在于您希望它的工作方式与您输入值并按enter键生成换行符一样,然后您尝试使用其文档中的.Quoting对其进行扫描:
输入中的换行符必须与格式中的换行符匹配
因此,如果要使用fmt.Scanf()
,格式字符串必须包含换行符\n
。但是,由于您的格式字符串不包含换行符,因此不会使用换行符,因此下一行读取值将自动进行
轻松修复:将\n
添加到格式字符串:
fmt.Println("Enter you choice:")
fmt.Println("1. PUSH\n2. POP\n3. PRINT\n4. EXIT")
fmt.Scanf("%d\n", &ch)
以及:
另一种方法是使用自动解析整行的:
fmt.Println("1. PUSH\n2. POP\n3. PRINT\n4. EXIT")
fmt.Scanln(&ch)
// ...
fmt.Println("Enter the value...")
fmt.Scanln(&temp)
另外,fmt.Scanf()
和fmt.Scanln()
返回成功扫描的数值和错误。确保检查这些数值以查看扫描是否成功
代码中的另一个错误是退出功能:您在案例4
分支中使用了break
语句。break
只会断开开关,而不会断开的!因此请使用return
而不是break
:
case 4:
return
另一个修复方法是使用标签,还请注意,for true{…}
等同于for{…}
(您可以省略true
):
case 4:
return
mainloop:
for {
// ...
switch ch {
// ...
case 4:
break mainloop
// ...
}
}