C++: how can I test if a number is power of ten?

前端 未结 9 1264
清歌不尽
清歌不尽 2021-02-18 19:12

I want to test if a number double x is an integer power of 10. I could perhaps use cmath\'s log10 and then test if x == (int) x?

<

9条回答
  •  北恋
    北恋 (楼主)
    2021-02-18 19:31

    how about that:

    bool isPow10(double number, double epsilon)
    {
        if (number > 0)
        {
            for (int i=1; i <16; i++)
            {
                if ( (number >= (pow((double)10,i) - epsilon)) && 
                    (number <= (pow((double)10,i) + epsilon)))
                { 
                    return true;
                }
            }
        }
        return false;
    }
    

    I guess if performance is an issue the few values could be precomputed, with or without the epsilon according to the needs.

提交回复
热议问题