【问题标题】:Integer functions of square and square root平方和平方根的整数函数
【发布时间】:2015-03-04 10:19:29
【问题描述】:

目前,math.Pow()math.sqrt 采用 float64 类型参数。

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

【问题讨论】:

标签: go


【解决方案1】:

只需使用 int 值创建一个 float64 对象。例如 int = 10。

var x float64 = 10
var b = math.Pow(2, x) 

【讨论】:

    【解决方案2】:

    如果您的返回值是浮点数,您可以使用数学包中的 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() 中

    【讨论】:

      【解决方案3】:

      在 SO 的其他地方描述了快速近似算法,例如 this one。如果性能很重要,那么将其中一种 C 算法移植到 Go 中可能是值得的。

      【讨论】:

        【解决方案4】:

        您可以做的是将 float 类型转换为您的值。

        int a=10,b=2;
        math.Pow(float(a),float(b));
        

        【讨论】:

          猜你喜欢
          • 2013-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-28
          • 2013-03-01
          • 1970-01-01
          相关资源
          最近更新 更多