为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题
一个数的幂是该数自乘的结果。通常用一个底数和一个指数表示。底数表示被乘的数,指数表示底数被乘的次数。大多数计算机语言都有内置函数来求数字的幂。
这里我们展示如何在 Go 语言中求一个数的幂。这里变量 num 用于保存需要求幂的数字,另一个变量 exp 用于保存指数,以及 power 用于保存结果值。一个数的幂通过使用 math.Pow(num, exp) 求出。这里我们必须包含头文件 math 才能使用这个内置函数。下面是 Go 程序中使用的步骤。
步骤 1:导入 fmt, math 包
第二步:启动 main() 函数
步骤 3:声明变量 num, exp
步骤 4:使用 `fmt.Scanfln()` 读取数字 num
步骤 5:使用 fmt.Scanfln() 读取指数 exp
步骤 6:使用 math.Pow(num, exp) 求一个数的幂
步骤 7:将结果保存到变量 power 中
步骤 7:使用 fmt.Println() 打印结果 power
package main
import (
"fmt"
"math"
)
func main() {
var num, exp, power float64
fmt.Print("\nEnter the number to find the Power = ")
fmt.Scanln(& num)
fmt.Print("\nEnter the exp = ")
fmt.Scanln(& exp)
power = math.Pow(num, exp)
fmt.Print(num ,"Power", exp, " = ", power)
}
Enter the number to find the Power = 3 Enter the exp = 4 3 Power 4 = 81