Golang math.Float32frombits()的作用及示例
Go语言提供了math包内置的基本常量和数学函数来对数字进行操作。该包提供了 Float32frombits()函数 ,它返回与a的IEEE 754二进制表示相对应的浮点数,其中a的符号位和结果在相同的位位置。因此,您需要使用import关键字在程序中添加一个math包来访问Float32frombits()函数。
语法:
func Float32frombits(a uint32) float32
示例1:
// Golang program to illustrate how to find
// the floating-point number corresponding
// to the IEEE 754 binary representation
package main
import (
"fmt"
"math"
)
// Main function
func main() {
// Finding floating-point number corresponding
// to the IEEE 754 binary representation
// of the given numbers
// Using Float32frombits() function
res_1 := math.Float32frombits(2)
res_2 := math.Float32frombits(1)
res_3 := math.Float32frombits(0)
res_4 := math.Float32frombits(223)
// Displaying the result
fmt.Println("Result 1: ", res_1)
fmt.Println("Result 2: ", res_2)
fmt.Println("Result 3: ", res_3)
fmt.Println("Result 4: ", res_4)
}
输出:
Result 1: 3e-45
Result 2: 1e-45
Result 3: 0
Result 4: 3.12e-43
示例2:
// Golang program to illustrate how to find
// the floating-point number corresponding
// to the IEEE 754 binary representation
package main
import (
"fmt"
"math"
)
// Main function
func main() {
// Finding floating-point number corresponding
// to the IEEE 754 binary representation
// of the given numbers
// Using Float32frombits() function
nvalue_1 := math.Float32frombits(3)
nvalue_2 := math.Float32frombits(50)
// Sum of the given values
res := nvalue_1 + nvalue_2
fmt.Println("Result 1: ", nvalue_1)
fmt.Println("Result 2: ", nvalue_2)
fmt.Println("Sum of Result 1 and Result 2: ", res)
}
输出:
Result 1: 4e-45
Result 2: 7e-44
Sum of Result 1 and Result 2: 7.4e-44