Home > Article > Backend Development > How to count the number of digits in C language
In C language, the method of calculating the number of digits is to define the number of digits variable. Use a while loop to continuously divide by 10 and increment the number of bits variable. When the number divided by 10 becomes 0, the loop stops and the digits variable is returned.
How to calculate the number of digits in a number
In C language, you can use the following method to calculate the number of digits in a number :
Method:
while
loop to continuously divide by 10 and increment the number of bits variable in the loop. Code example:
<code class="c">#include <stdio.h> int countDigits(int num) { int count = 0; while (num > 0) { count++; num /= 10; } return count; } int main() { int number; printf("请输入一个整数:"); scanf("%d", &number); printf("该整数的位数为:%d\n", countDigits(number)); return 0; }</code>
Explanation:
countDigits()
The function accepts an integer parameter and returns its number of digits. while
loop to continuously divide by 10 and increment the count
variable. count
variable. main()
The function gets an integer from the user and prints its digits. The above is the detailed content of How to count the number of digits in C language. For more information, please follow other related articles on the PHP Chinese website!