[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上,计算精度的问题。

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

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

posted @ 2017-06-12 13:41  战侠歌1994  阅读(793)  评论(0编辑  收藏  举报