-3
package main

import (
    "fmt"
    "math"
)

func main() {

    distencecalc()
}

func distencecalc() {

    fmt.Println("X1 :")
    var x1 float64
    fmt.Scanf("%f", &x1)
    fmt.Print("")
    fmt.Println("Y1 :")
    var y1 float64
    fmt.Scanf("%f", &y1)
    fmt.Print("")
    fmt.Println("Z1 :")
    var z1 float64
    fmt.Scanf("%f", &z1)
    fmt.Print("")
    fmt.Println("X2 :")
    var x2 float64
    fmt.Scanf("%f", &x2)
    fmt.Print("")
    fmt.Println("Y2 :")
    var y2 float64
    fmt.Scanf("%f", &y2)
    fmt.Print("")

    fmt.Println("Z2 :")
    var z2 float64
    fmt.Scanf("%f", &z2)
    fmt.Print("")

    var Xcalc = x2 - x1
    var Ycalc = y2 - y1
    var Zcalc = z2 - z1



    var calcX = math.Pow(Xcalc, 2)
    var calcY = math.Pow(Ycalc, 2)
    var calcZ = math.Pow(Zcalc, 2)


    var allcalc = calcX + calcZ + calcY
    fmt.Println("the result is :")
    fmt.Println(math.Sqrt(allcalc))
}

The problem is I compile then run the program it asks about x1 I enter the value and it asks about y1 and z1 at the same time.

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30

1 Answers1

2

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)
}
icza
  • 389,944
  • 63
  • 907
  • 827