为什么我的循环不按照描述的顺序执行命令

现在我正在努力学习围棋。


我有代码:


package main


import (

    "bufio"

    "fmt"

    "os"

)


func main() {

    var wallCount int

    var width, height, area float64

    var r = bufio.NewReader(os.Stdin)

    fmt.Print("WallCount:")

    fmt.Scanf("%d", &wallCount)

    fmt.Printf("wallcount =  %v \n", wallCount)

    for x := 1; x <= wallCount; x++ {

        fmt.Printf("wight, height at %v times\n", x)

        fmt.Fscanf(r, "%d %d", &width, &height)

        area += width * height

    }


    fmt.Printf("area =  %v\n", area)


}


当我编译代码时


在终端上:


WallCount:

进入第 4 学期


WallCount:4

---

wallcount =  4

wight, height at 1 times

wight, height at 2 times

传递到第 1,1 项


WallCount:4

wallcount =  4

wight, height at 1 times

wight, height at 2 times

1,1

---

wight, height at 3 times

wight, height at 4 times

area =  0

你能解释一下吗

  1. 为什么我for loops运行第一个 cmd 两次,然后运行第二个 cmd,然后再次运行第一个 cmd 两次,最后运行最后一个 cmd?

  2. 为什么area包含 0 ?


梵蒂冈之花
浏览 151回答 1
1回答

红颜莎娜

这里有一些问题。首先,您使用%d了表示整数值的 ,而您使用的是浮点值(使用%f)。此函数:fmt.Fscanf(r, "%d %d", &width, &height)返回两个值。第一个值是它成功解析的项目数,第二个值是一个错误。您应该始终检查返回的错误是否不是nil,这意味着有错误:func main() {&nbsp; &nbsp; var wallCount int&nbsp; &nbsp; var width, height, area float64&nbsp; &nbsp; var r = bufio.NewReader(os.Stdin)&nbsp; &nbsp; fmt.Print("WallCount:")&nbsp; &nbsp; fmt.Scanf("%d", &wallCount)&nbsp; &nbsp; fmt.Printf("wallcount =&nbsp; %v \n", wallCount)&nbsp; &nbsp; for x := 1; x <= wallCount; x++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("wight, height at %v times\n", x)&nbsp; &nbsp; &nbsp; &nbsp; _, err := fmt.Fscanf(r, "%f %f\n", &width, &height)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; area += width * height&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("area =&nbsp; %v\n", area)}在这种情况下,错误非常清楚地描述出了什么问题,即:bad verb '%d' for float64。在 go 中,这种检查错误是否为 nil 的形式非常常见,您应该始终检查错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go