[Solved] Tell me what’s wrong with this code GOLANG


Actually the code in question works on unix systems, but usually the problem is that calls like fmt.Scanf("%f", &x1) does not consume newlines, but quoting from package doc of fmt: Scanning:

Scan, Fscan, Sscan treat newlines in the input as spaces.

And on Windows the newline is not a single \n character but \r\n, so the subsequent fmt.Scanf() call will proceed immediately without waiting for further input from the user.

So you have to add a newline to your format string to avoid subsequent fmt.Scanf() call to proceed:

fmt.Scanf("%f\n", &x1)

But easier would be to just use fmt.Scanln() and skip the whole format string:

fmt.Scanln(&x1)

Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.

The scanner functions (fmt.ScanXXX()) return you the number of successfully scanned items and an error. To tell if scanning succeeded, you have to check its return value, e.g.:

if _, err := fmt.Scanln(&x1); err != nil {
    fmt.Println("Scanning failed:", err)
}

solved Tell me what’s wrong with this code GOLANG