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

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

    bool power_of_ten(double x) {
       if(x < 1.0 || x > 10E15) {
          warning("IEEE754 doubles can only precisely represent powers "
                  "of ten between 1 and 10E15, answer will be approximate.");
       }
       double exponent;
       // power of ten if log10 of absolute value has no fractional part
       return !modf(log10(fabs(x)), &exponent);
    }
    

提交回复
热议问题