小编Sta*_*nge的帖子

使用switch case语句在fizzbuzz上混淆输出

这里着名的"fizz buzz"程序在Go中使用switch/case和if/else条件.问题是使用switch/case会产生意外的输出,而if/else(具有相同的条件)工作正常.我知道golang中的switch/case与其他C系列语言不同,但是这个代码片段有什么问题?

func main() {
const (
    FIZZ = 3
    BUZZ = 5
)

//section with switch/case gives unexpected output
for i := 1; i <= 30; i++ {
    switch {
    case i % FIZZ == 0:
        fmt.Printf("%d fizz\t", i%3)
        fallthrough
    case i % BUZZ == 0:
        fmt.Printf("%d buzz\t", i%5)
    }
    fmt.Printf("\t%d\n", i)
}

fmt.Printf("now towards the if/else\n")

//section with if/else works as expected
for i := 1; i <= 30; i++ {
    if i % FIZZ == 0 { …
Run Code Online (Sandbox Code Playgroud)

conditional fizzbuzz go fall-through

5
推荐指数
1
解决办法
1476
查看次数

标签 统计

conditional ×1

fall-through ×1

fizzbuzz ×1

go ×1