Golang 找到给定数字的平方根
Go语言提供了基本常量和数学函数的内置支持,可以通过math包执行对数字的操作来查找指定数字的平方根,利用math包中的Sqrt()函数即可。因此,您需要使用import关键字在程序中添加math包以访问Sqrt()函数。
语法:
func Sqrt(a float64) float64
- 如果在此函数中传入+Inf,那么此函数将返回+Inf。
- 如果在此函数中传入+0或-0,则此函数将返回+0或-0。
- 如果a<-1的值,则此函数将返回NaN。
- 如果在此函数中传入NaN,则此函数将返回NaN。
示例1:
// Golang程序演示如何查找给定数字的平方根
package main
import (
"fmt"
"math"
)
// Main函数
func main() {
// 找到给定数字的平方根
// 使用Sqrt()函数
res_1 := math.Sqrt(0)
res_2 := math.Sqrt(-100)
res_3 := math.Sqrt(math.Inf(1))
res_4 := math.Sqrt(math.NaN())
res_5 := math.Sqrt(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:0.0
结果2:NaN
结果3:+Inf
结果4:NaN
结果5:6.0
示例2:
// Golang程序演示如何查找给定数字的平方根
package main
import (
"fmt"
"math"
)
// Main函数
func main() {
// 找到给定数字的平方根
// 使用Sqrt()函数
nvalue_1 := math.Sqrt(100)
nvalue_2 := math.Sqrt(25)
res := nvalue_1 + nvalue_2
fmt.Printf("%.3f + %.3f = %.3f",
nvalue_1, nvalue_2, res)
}
输出:
10.000 + 5.000 = 15.000