猿问

golang 运算符 % 未在 float64 上定义

有一个 leetcode 测试326。使用 java 的数学方法的三的幂:


public class Solution {

    public boolean isPowerOfThree(int n) {

        return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;

    }

}

当我打算将此解决方案转换为 Golang Like


import "math"


func isPowerOfThree(n int) bool {

    return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0 

}

然后出现编译错误,例如


Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)

我检查了数学包,但没有像运算符这样受支持的函数,有没有像Golang这样的%有效运算符?%多谢 :)


守候你守候我
浏览 352回答 1
1回答

有只小跳蛙

TLDR: _, frac := math.Modf(f)您可以func Mod(x, y float64) float64在math包装中使用。package mainimport (&nbsp; &nbsp; "math")func isPowerOfThree(n int) bool {&nbsp; &nbsp; return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0&nbsp;}你也可以使用func Modf(f float64) (int float64, frac float64).package mainimport (&nbsp; &nbsp; "math")func isPowerOfThree(n int) bool {&nbsp; &nbsp; _, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))&nbsp; &nbsp; return frac == 0.0}
随时随地看视频慕课网APP

相关分类

Go
我要回答