Home > Back-end >  Why does go give me this result?
Why does go give me this result?

Time:02-06

I am making a program that calculates the percentage of males and females in the class. But it gives me an incorrect result.

The code is:

package main
import {
    "fmt"
}

var total, mujeres, hombres float64

func main() {
    fmt.Printf("Número de mujeres:")
    fmt.Scanln(&mujeres)

    fmt.Printf("Número de hombres:")
    fmt.Scanln(&hombres)

    total = mujeres   hombres
    mujeres = (mujeres / total) * 100
    hombres = (hombres / total) * 100

    print("En al salón de clases hay ", mujeres, "% de mujeres y ", 
        hombres, "% de hombres")
}

And the output I'm getting when entering 50 for both quantities is:

En al salón de clases hay  5.000000 001% de mujeres y  5.000000 001% de hombres

I want to know what causes this problem and how to solve it.

CodePudding user response:

It's not giving an incorrect result, it's giving the correct result in an incorrect format. The value 5.000000e 001 is 5x101, which is equal to 50.

If you want them formatted differently to the default, you need to specify that, such as with:

fmt.Printf("En al salón de clases hay %.1f%% du mujeres y %.1f%% du hombres\n",
    mujeres, hombres)
  • Related