Golang 查找指定数字的立方根

Golang 查找指定数字的立方根

Go语言提供了基本常量和数学函数的内置支持,可以使用math包中的Cbrt()函数执行数字操作。因此,您需要通过import关键字在程序中添加math包以访问Cbrt()函数,从而可以找到指定数字的立方根。

语法:

func Cbrt(y float64) float64
  • 如果您在此函数中传递+Inf或-Inf,则此函数将返回+Inf或-Inf。
  • 如果您在此函数中传递0,则此函数将返回0。
  • 如果您在此函数中传递NaN(不是数字),则此函数将返回NaN。

示例1:

// Golang程序演示如何查找
// 给定数字的立方根
   
package main
   
import (
    "fmt"
    "math"
)
   
// 主函数
func main() {
   
    // 查找给定值的立方根
    // 使用Cbrt()函数
    res_1 := math.Cbrt(3)
    res_2 := math.Cbrt(math.Inf(-3))
    res_3 := math.Cbrt(0)
    res_4 := math.Cbrt(math.NaN())
   
    // 显示结果
    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)
} 

输出:

Result 1: 1.4
Result 2: -Inf
Result 3: 0.0
Result 4: NaN

示例2:

// Golang程序演示如何查找
// 给定数字的立方根
   
package main
   
import (
    "fmt"
    "math"
)
   
// 主函数
func main() {
   
    // 查找给定数字的立方根
    nvalue_1 := math.Cbrt(3)
    nvalue_2 := math.Cbrt(-7)
   
    // 给定值的和
    res := nvalue_1 + nvalue_2
   
    // 显示结果
    fmt.Printf("%.1f + %.1f = %.1f",
            nvalue_1, nvalue_2, res)
   
} 

输出:

1.4 + -1.9 = -0.5

时间复杂度: O(log N)

辅助空间: O(1)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程