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

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

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

语法:

func Log2(a float64)float64
  • 如果将+ Inf传递给此函数,则此函数将返回+ Inf。
  • 如果将0传递给此函数,则此函数将返回-Inf。
  • 如果a的值<0,则此函数将返回NaN。
  • 如果将NaN传递给此函数,则此函数将返回NaN。

示例1:

// Golang program to illustrate how to find the
// binary logarithm of the given number
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding binary logarithm
    // of the given number
    // Using Log2() function
    res_1 := math.Log2(0)
    res_2 := math.Log2(1)
    res_3 := math.Log2(math.Inf(1))
    res_4 := math.Log2(math.NaN())
    res_5 := math.Log2(36)
  
    // Displaying the result
    fmt.Printf("Result 1: %.1f", res_1)
    fmt.Printf("\nResult 2: %.1f", res_2)
    fmt.Printf("\nResult 3: %.1f", res_3)
    fmt.Printf("\nResult 4: %.1f", res_4)
    fmt.Printf("\nResult 5: %.1f", res_5)
  
} 

输出:

Result 1: -Inf
Result 2: 0.0
Result 3: +Inf
Result 4: NaN
Result 5: 5.2

示例2:

// Golang program to illustrate how to find the
// binary logarithm of the given number
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding binary logarithm
    // of the given number
    // Using Log2() function
    nvalue_1 := math.Log2(100)
    nvalue_2 := math.Log2(26)
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.5f + %.5f = %.5f",
            nvalue_1, nvalue_2, res)
  
} 

输出:

6.64386 + 4.70044 = 11.34430

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程