平方和平方根的整数函数

cal*_*tie 5 go

当前,math.Pow()math.sqrt接受float64类型参数。

我们是否有接受int类型参数的等效函数?

小智 5

如果返回值是浮点数,则可以使用 math 包中的 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
Run Code Online (Sandbox Code Playgroud)

请记住,Floor 仍然返回 float64,因此您仍然需要将其包装在 int() 中


小智 -3

您可以做的是将浮点数类型转换为您的值。

int a=10,b=2;
math.Pow(float(a),float(b));
Run Code Online (Sandbox Code Playgroud)