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

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

    if you don't need it to be fast, use recursion. Pseudocode:

    bool checkifpoweroften(double Candidadte)
         if Candidate>=10
             return (checkifpoweroften(Candidadte/10) 
         elsif Candidate<=0.1
             return (checkifpoweroften(Candidadte*10)
         elsif Candidate == 1
             return 1
         else 
             return 0
    

    You still need to choose between false positives and false negatives and add tolerances accordingly, as other answers pointed out. The tolerances should apply to all comparisons, or else, for exemple, 9.99999999 would fail the >=10 comparison.

提交回复
热议问题