英文:
I have been trying to print out this code, and it keeps popping out an error
问题
我一直在尝试打印这段代码,但是一直弹出一个错误消息。。
package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
switch {
case i%15 == 0:
fmt.Println("FizzyBuzz")
case i%3 == 0:
fmt.Println("Fizzy")
case i%5 == 0:
fmt.Println("Buzz")
default:
fmt.Println(i)
}
}
}
这是代码。
英文:
I've been trying to print this out, but keeps popping out an error message..
package main
import "fmt"
func main() {
for i:= 1; i<= 100; i++
switch i {
case i % 15 == 0:
fmt.Println("FizzyBuzz")
case i % 3 == 0:
fmt.Println("Fizzy")
case i % 5 == 0:
fmt.Println("Buzz")
default :
fmt.Println(i)
}
}
This is the code.
答案1
得分: 2
你的代码有两个问题。
首先,for语句缺少开放和闭合的大括号。
其次,switch语句的使用是错误的。实际上,你应该为每个你想要评估的情况指定一个值,而不是变量i
。如果你想要评估条件(例如,i % 15 == 0
),应该使用if-else语句。
修正后的代码如下所示:
package main
import "fmt"
func main() {
for i:= 1; i<= 100; i++ {
if i % 15 == 0 {
fmt.Println("FizzyBuzz")
} else if i % 3 == 0 {
fmt.Println("Buzz")
} else if i % 5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}
英文:
There are two issues with your code.
First of all, the for statement is missing its opening and closing curly brackets.
Then, the usage of the switch statement is wrong. You are, in fact, supposed to specify a value for the i
variable for each of the cases that you want to evaluate. If you want to evaluate conditions (for example, i % 15 == 0
), the if-else statement will be the right choice.
The code would then be like as follows:
package main
import "fmt"
func main() {
for i:= 1; i<= 100; i++ {
if i % 15 == 0 {
fmt.Println("FizzyBuzz")
} else if i % 3 == 0 {
fmt.Println("Buzz")
} else if i % 5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}
答案2
得分: 1
你正在尝试将布尔值添加到case语句中,但case语句期望与switch语句中的比较变量具有相同类型的值(在这里你传递了整数i),而你却传递了布尔值给case语句。我建议在这里使用if else语句而不是switch case语句。
请查看此链接以获取有关Golang中switch case语句的更多信息这里。
英文:
You are trying to add a bool values to the case statements, the case statements expects a value wit with the same type as the comparison variable at the switch statement [ Here you passed i, which is integer ] and you passed a boolean to the case statements. I would recommend to use if else here instead of switch case.
Please checkout this link for more information about switch case statement in Golang here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论