+ 2
Constant Truncated to Integer Error [solved]
package main import "fmt" func mars_age(age int) int { return (age/1.88) } func main() { var age int fmt.Scanln(&age) mars := mars_age(age) fmt.Println(mars) } Can you guys let me know wats wrong with 1.88 integer? I also tried to take that value in a var but same issue.
2 Respuestas
+ 5
Truncated means losing decimals (1.88 -> 1)
This happens if we use integer datatype instead of floats
Try this
package main
import "fmt"
func mars_age(age float32) float32 {
return (age/1.88)
}
func main() {
var age float32
fmt.Scanln(&age)
mars := mars_age(age)
fmt.Println(mars)
}
+ 2
In your mars_age function 1.88 is a float constant and age is an int. When 1 of the operands of division is an int, then the result of division would be an int and the decimal portion would be implicitly truncated. So, for instance, if age were 35 then the normal result of division would be 18.6170212766, but the truncated (int) result would be 18. This means that the truncated portion would also result in an inaccuracy or a loss of information. This type of lossy performance is not implicitly allowed in Go. You need to do an explicit conversion of age in order to complete the division without error. If you want to return the number without truncating the fractional portion then you can do so like;
func mars_age(age int) float64 {
return float64(age)/1.88
}
If you would like to complete the division and then truncate the fractional portion so as to return an int from the function you can do so like this;
func mars_age(age int) int {
return int(float64(age)/1.88)
}