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

前端 未结 9 1266
清歌不尽
清歌不尽 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 
    #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.

提交回复
热议问题