[C++] log函数的一点小问题

log函数的一点小问题

在cppreference中

    #include<cmath>
    float log( float arg ); 
    double log( double arg );
    long double log( long double arg );
    double log( Integral arg );

1-3) Computes the the natural (base e) logarithm of arg.
4) A set of overloads or a function template accepting an argument of any integral type. Equivalent to 2) (the argument is cast to double).

    #include<math.h>
    float logf( float arg );
    double log( double arg );
    long double logl( long double arg );
    #define log( arg )

1-3) Computes the natural (base e) logarithm of arg.
4) Type-generic macro: If arg has type long double, logl is called. Otherwise, if arg has integer type or the type double, log is called. Otherwise, logf is called. If arg is complex or imaginary, then the macro invokes the corresponding complex function (clogf, clog, clogl).

在刷leetcode的Power of Three时,一直A不过去,转到VS中debug了一下,发现问题了。

Given an integer, write a function to determine if it is a power of three.

A不过去的代码是
    bool isPowerOfThree(int n) {
        if(n <= 0) return false;
        return n == pow(3,int(log(n)/log(3)));
    }
能A过去的代码是
    bool isPowerOfThree(int n) {
        if(n <= 0) return false;
        return n == pow(3,int(logf(n)/logf(3)));
    }

发现区别了么?
loglogf上,计算精度的问题。
Izk8enp.png

但是在紧接着的下一题Power of Two时,提交上一题能A的代码又过不去了,但是上一题不能A过去的代码能A过去了。
搞的我有点懵圈啊。

为了避免此问题精度问题,在使用对数函数是,尽量使用log10

转载于:https://www.cnblogs.com/zhanxiage1994/p/6992540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值