为了账号安全,请及时绑定邮箱和手机立即绑定

golang 运算符 % 未在 float64 上定义

golang 运算符 % 未在 float64 上定义

Go
守候你守候我 2022-06-13 16:35:54
有一个 leetcode 测试326。使用 java 的数学方法的三的幂:public class Solution {    public boolean isPowerOfThree(int n) {        return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;    }}当我打算将此解决方案转换为 Golang Likeimport "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这样的%有效运算符?%多谢 :)
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

TLDR: _, frac := math.Modf(f)


您可以func Mod(x, y float64) float64在math包装中使用。


package main


import (

    "math"

)


func isPowerOfThree(n int) bool {

    return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0 

}

你也可以使用func Modf(f float64) (int float64, frac float64).


package main


import (

    "math"

)


func isPowerOfThree(n int) bool {

    _, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))

    return frac == 0.0

}


查看完整回答
反对 回复 2022-06-13
  • 1 回答
  • 0 关注
  • 351 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号