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

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

    How about a code like this:

    
    #include <stdio.h>
    #define MAX 20
    bool check_pow10(double num)
    {
       char arr[MAX];
       sprintf(arr,"%lf",num);
       char* ptr = arr;
       bool isFirstOne = true;
    
       while (*ptr)
       {
         switch (*ptr++)
         {
           case '1':
                    if (isFirstOne)
                       isFirstOne = false;
                    else
                       return false;
                    break;
           case '0':
                    break;
           case '.':
                    break;
           default:
                    return false;
         }
       }
    
     return true;
    }
    
    int main()
    {
      double number;
      scanf("%lf",&number);
      printf("isPower10: %s\n",check_pow10(number)?"yes":"no");
    }
    

    That would not work for negative powers of 10 though.
    EDIT: works for negative powers also.

    0 讨论(0)
  • 2021-02-18 19:39

    A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.

    This has the advantage that you will get a "hit" if and only if your number is exactly the closest possible IEEE double to some power of 10. If this isn't what you want, you need to be more precise about exactly how you would like your solution to handle the fact that many powers of 10 can't be exactly represented as doubles.

    The best way to construct the table is probably to use string -> float conversion; that way hopefully your library authors will already have solved the problem of how to do the conversion in a way that gives the most precise answer possible.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题