是否可以在不使用数学库的情况下计算功率值?

我想知道我们如何使用math库计算功率值?

我已经检查了大多数方法都是使用math库来实现的计算功率值的方法(即,math.Pow)。

例如,如果我们想计算 3^2,我们可以像3**2在 Python 中那样做,所以我很好奇是否可以通过数学符号做类似 Python 的方式来在 Go 中计算它?

谢谢!


白板的微信
浏览 161回答 2
2回答

交互式爱情

没有 Go 运算符(“数学符号”)可以执行此操作,但如果指数是常数,您当然可以只写x*xx^2 或x*x*xx^3。如果指数不是常量而是整数,计算 n^exp 的一种简单方法是使用重复乘法,如下所示:func pow(n float64, exp int) float64 {&nbsp; &nbsp; if exp < 0 { // handle negative exponents&nbsp; &nbsp; &nbsp; &nbsp; n = 1 / n&nbsp; &nbsp; &nbsp; &nbsp; exp = -exp&nbsp; &nbsp; }&nbsp; &nbsp; result := 1.0&nbsp; &nbsp; for i := 0; i < exp; i++ {&nbsp; &nbsp; &nbsp; &nbsp; result *= n&nbsp; &nbsp; }&nbsp; &nbsp; return result}也就是说,我不确定您为什么要避免math.Pow使用它——它在标准库中,而且速度更快、更通用。

皈依舞

如果数字是整数,那么这应该有效:package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; number := 4&nbsp; &nbsp; power := 5&nbsp; &nbsp; result := 1&nbsp; &nbsp; for power != 0 {&nbsp; &nbsp; &nbsp; &nbsp; result = result * number&nbsp; &nbsp; &nbsp; &nbsp; power = power - 1&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(result)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go