计算给定正数的总位数,而不在C中循环

Sam*_*Sol 2 c

如何计算给定正数的总位数而不在C中循环?

pto*_*ato 6

对于整数,取数字的log10,向下舍入,然后添加一个.

测试:

#include <math.h>
#include <stdio.h>

int 
num_digits(unsigned long number)
{
    return (int)(floor(log10((double)number)) + 1.0);
}

int
main(int argc, char **argv)
{
    unsigned long test_numbers[] = {
        1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, 999999,
        123456789ul,
        999999999ul,
        0
    };

    unsigned long *ptr;
    for(ptr = test_numbers; *ptr; ptr++)
    {
        printf("Number of digits in %lu: %d\n", *ptr, num_digits(*ptr));
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Number of digits in 1: 1
Number of digits in 9: 1
Number of digits in 10: 2
Number of digits in 99: 2
Number of digits in 100: 3
Number of digits in 999: 3
Number of digits in 1000: 4
Number of digits in 9999: 4
Number of digits in 10000: 5
Number of digits in 99999: 5
Number of digits in 100000: 6
Number of digits in 999999: 6
Number of digits in 123456789: 9
Number of digits in 999999999: 9
Run Code Online (Sandbox Code Playgroud)