-1

First of all i'm new to programming, and i have problem. I'm trying to take 1/4 from a float but it doesn't work (it has to be a float this is just an easier example).

package main

import (
    "fmt"
)

var (
    a float64
)

func main() {

    fmt.Println("digit")
    fmt.Scan(&a)

    s := a * (1 / 4)
    fmt.Println(s)
}

If the input is 100 it returns 0.

PunPun
  • 17
  • 4
  • 3
    The constant expression `(1/4)` evaluates to zero. See question [How to perform division in Go](https://stackoverflow.com/q/32815400/5728991) for more info. – Charlie Tumahai Nov 30 '21 at 21:46
  • 3
    nice job on the completeness of your example @PunPun - I wish we saw more such minimal, verifiable examples on SO – erik258 Nov 30 '21 at 23:01

1 Answers1

4

You are dividing two integers, not floats. The fact that you later assign it to float64 changes nothin. You need to use decimal point in at least one value to inform Go compiler it should do floating point division:

package main

import (
    "fmt"
)

var (
    a float64
)

func main() {

    fmt.Println("digit")
    fmt.Scan(&a)

    s := a * (1.0 / 4)
    fmt.Println(s)
}
Hauleth
  • 22,873
  • 4
  • 61
  • 112