Golang程序求一个数的平方根


2022 年 3 月 4 日, Learn eTutorial
1715

为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题

什么是数的平方根?

一个数的平方根就是自身相乘得到原数的那个数。

如何求一个数的平方根

大多数编程语言都有预定义的数学函数来求给定数字的平方根。

如何在Go程序中求一个数的平方根

这里我们展示如何在Go语言中求一个数的平方根。其中变量 **num** 用于存储需要求平方根的数字,另一个变量 **sqrt** 用于存储结果。通过使用 **math.Sqrt(num)** 来求数字的平方根。这里我们必须包含头文件 **math** 才能使用这个内置函数。下面是Go程序中使用的步骤。

算法

步骤 1:导入 fmt, math

第二步:启动 main() 函数

步骤 3:声明变量 **num, sqrt**

步骤 4:使用 `fmt.Scanfln()` 读取数字 num

步骤 5:使用 **math.Sqrt(num)** 求数字 num 的平方根

步骤 6:将结果保存到变量 **sqrt** 中

步骤 7:使用 fmt.Println() 打印结果

 

Golang 源代码

                                          package main

import (
    "fmt"
    "math"
)

func main() {

    var n, sqrt float64

    fmt.Print("\nEnter the number to find Square root = ")
    fmt.Scanln(&n)

    sqrt = math.Sqrt(n)

    fmt.Println("\nThe Square root of a number = ", sqrt)
}
                                      

输出

Enter the number to find Square root = 81

The Square root of a number  = 9