-6

the output should be a valid number not 0 but i get 0 as output, i looked every where, docs, stackoverflow, gfg and i didn;t find anything, please help me. this is my code, please help (the output must be 'weight / (height * height)* 10000))

package main
import "fmt"

func calculate(height int, weight int) int{
    var x = height * height
    var y = weight
    var z = y / x
    var n = z * 10000
    return n
}

func main() {
    fmt.Println(calculate(160, 40))
}
NOT kar1m yt
  • 188
  • 3

2 Answers2

1

If you have a requirement that your function must return an int, then I think your simplest solution is this

func calculate(height, weight int) int {
   return weight * 10000 / (height * height)
}

Take advantage of the commutative property of multiplication, that is:

weight / (height * height) * 10000

is equal (in ideal mathematical terms) to

weight * 10000 / (height * height)

The advantage the second option comes when you are working with integers. When you divide integers in Go, you lose information as you don't retain the remainder. Since we've assumed that you must return an integer, you must have a loss of information at some point due to the division. By moving the division operation to the last step in the order of operations, we minimize the impact of this error.

Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33
-1

You can do a bunch of casts:

package main

func calculate(height, weight int) int {
   z := float32(weight) / float32(height * height)
   return int(z * 10000)
}

func main() {
   println(calculate(160, 40) == 15)
}

or you can define the function as taking float arguments:

package main

func calculate(height, weight float32) float32 {
   x := height * height
   z := weight / x
   return z * 10000
}

func main() {
   println(calculate(160, 40) == 15.625)
}

https://golang.org/ref/spec#Arithmetic_operators

Zombo
  • 1
  • 62
  • 391
  • 407