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

前端 未结 9 1254
清歌不尽
清歌不尽 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:17

    Your solution sounds good but I would replace the exact comparison with a tolerance one.

    double exponent = log10(value);
    double rounded = floor(exponent + 0.5);
    if (fabs(exponent - rounded) < some_tolerance) {
        //Power of ten
    }
    

提交回复
热议问题