Golang 找到给定数字的二进制指数

Golang 找到给定数字的二进制指数

Go 语言提供了基本常量和数学函数的内置支持,可借助 math 包执行数字操作。使用 math 包中提供的 Logb() 函数,您可以找到指定数字的二进制指数。因此,您需要使用 import 关键字在程序中添加 math 包以访问 Logb() 函数。

语法:

func Logb(a float64) float64
  • 如果您在此函数中传递 +Inf 或 -Inf,则此函数将返回 +Inf。
  • 如果您在此函数中传递 0,则此函数将返回 -Inf。
  • 如果您在此函数中传递 NaN,则此函数将返回 NaN。

示例 1:

// Golang 程序示例,演示如何查找给定数字的
// 二进制指数
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main 函数
func main() {
  
    // 查找二进制指数
    // Using Logb() function
    res_1 := math.Logb(0)
    res_2 := math.Logb(1)
    res_3 := math.Logb(math.Inf(1))
    res_4 := math.Logb(math.NaN())
    res_5 := math.Logb(36)
  
    // 显示结果
    fmt.Printf("结果 1:%.1f", res_1)
    fmt.Printf("\n结果 2:%.1f", res_2)
    fmt.Printf("\n结果 3:%.1f", res_3)
    fmt.Printf("\n结果 4:%.1f", res_4)
    fmt.Printf("\n结果 5:%.1f", res_5)
  
} 

输出:

结果 1:-Inf
结果 2:0.0
结果 3:+Inf
结果 4:NaN
结果 5:5.0

示例 2:

// Golang 程序示例,演示如何查找给定数字的
// 二进制指数
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main 函数
func main() {
  
    // 查找二进制指数
    // Using Logb() function
    nvalue_1 := math.Logb(100)
    nvalue_2 := math.Logb(26)
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.5f + %.5f = %.5f",
            nvalue_1, nvalue_2, res)
  
} 

输出:

6.00000 + 4.00000 = 10.00000

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程