Type conversion for converting one type to another type of variable variable.
The following scene:
package main import "fmt" func main() { var sum int = 17 var count int = 5 mean := sum / count fmt.Printf("mean 的值为: %f\n", mean) }
Output: mean value:!% F (int = 3)
The above code, the variables sum and count are integers, for division by two variables, because not divisible, it should be a floating point number, but the resulting 3 is an integer, so there need to use a type conversion, first the sum and count variable into float32 type, and then make the division, get what we want accurate float up. code show as below:
package main import "fmt" func main() { var sum int = 17 var count int = 5 mean := float32(sum) / float32(count) fmt.Printf("mean 的值为: %f\n", mean) }
Output: mean value: 3.400000