How can the C programming language determine the number of digits in a number?

To determine the number of digits in a number, you can keep dividing by 10 until the result is less than 1. The specific method is as follows:

  1. Define a variable called count to keep track of the number of digits with an initial value of 0.
  2. Divide by 10 repeatedly until the dividend is zero. In each iteration, the dividend is divided by 10 and count is incremented by 1.
  3. Finally, the value of ‘count’ is the number of digits in the number.

Here is an example code:

#include <stdio.h>

int main() {
    int num;
    int count = 0;
    
    printf("请输入一个整数:");
    scanf("%d", &num);
    
    // 判断num的位数
    do {
        num /= 10;
        count++;
    } while (num != 0);
    
    printf("该数是%d位数\n", count);
    
    return 0;
}

Run example:
Please input an integer: 12345
The number has 5 digits.

bannerAds