Why does my loop execute commands not in the order they are described

Issue

Now i’m trying to learn go.

I’m have code:

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)

}

When i’m compiling code

On a terminal:

WallCount:

passing to term 4

WallCount:4
---
wallcount =  4
wight, height at 1 times
wight, height at 2 times

passing to term 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

Can u please explain me

  1. why my for loops running first cmd twice then running second cmd then again first cmd twice and finally runs the last cmd?
  2. why area contains 0 ?

Solution

There are a few things going wrong here. First of all, you used %d, which denotes an integer value, while you are using float values (which use %f).

This function: fmt.Fscanf(r, "%d %d", &width, &height) returns two values. The first value is the number of items it has successfully parsed, and the second item is an error. You should always check if the error returned is not nil, this means that there was an error:

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)
        _, err := fmt.Fscanf(r, "%f %f\n", &width, &height)
        if err != nil {
            log.Println(err)
            return
        }
        area += width * height
    }

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

In this case, the error very clearly described what was wrong, namely: bad verb '%d' for float64. In go this form of checking if an error is nil is very common, and you should always check your errors.

Answered By – Thijs van der Heijden

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.