【发布时间】:2015-03-04 10:19:29
【问题描述】:
目前,math.Pow() 和 math.sqrt 采用 float64 类型参数。
我们是否有接受int 类型参数的等效函数?
【问题讨论】:
-
你可以在这里查看golang.org/pkg/math,它们没有提供。
标签: go
目前,math.Pow() 和 math.sqrt 采用 float64 类型参数。
我们是否有接受int 类型参数的等效函数?
【问题讨论】:
标签: go
只需使用 int 值创建一个 float64 对象。例如 int = 10。
var x float64 = 10
var b = math.Pow(2, x)
【讨论】:
如果您的返回值是浮点数,您可以使用数学包中的 Ceil 或 Floor,然后将其转换为 int。
n := 5.5
o := math.Floor(n)
p := int(math.Pow(o, 2))
fmt.Println("Float:", n)
fmt.Println("Floor:", o)
fmt.Println("Square:", p)
5.5
5
25
请记住,Floor 仍然返回一个 float64,因此您仍然需要将它包装在 int() 中
【讨论】:
在 SO 的其他地方描述了快速近似算法,例如 this one。如果性能很重要,那么将其中一种 C 算法移植到 Go 中可能是值得的。
【讨论】:
您可以做的是将 float 类型转换为您的值。
int a=10,b=2;
math.Pow(float(a),float(b));
【讨论】: