如何完善统计非负整数位数的C语言函数,使程序正常运行?
Hey there! Let's walk through fixing up your digit-counting function—since you're new to C, I'll keep this straightforward and break down every part so it clicks.
First, let's recap the requirement: we need a function that takes a non-negative integer, returns the number of digits. So input 563 → 3, input 0 → 1.
Common Pitfall to Fix First
Most beginners forget to handle the 0 case properly. Let's say you wrote something like this (super common first draft):
int countDigits(int num) { int count = 0; while (num > 0) { num = num / 10; count++; } return count; }
This works for numbers like 563 (returns 3) but fails for 0 (returns 0 instead of 1). That's the big fix we need to add.
Corrected Full Function
Here's the working version, with explanations for each part:
#include <stdio.h> // Use unsigned int to enforce non-negative input (more precise for our requirement) int countDigits(unsigned int num) { // Special case: 0 has exactly 1 digit if (num == 0) { return 1; } int count = 0; // Loop until we've stripped all digits from num while (num > 0) { num /= 10; // Same as num = num / 10; removes the last digit count++; // Increment count each time we remove a digit } return count; } // Test the function with different cases (run this to verify) int main() { printf("Digits in 563: %d\n", countDigits(563)); // Should print 3 printf("Digits in 0: %d\n", countDigits(0)); // Should print 1 printf("Digits in 9: %d\n", countDigits(9)); // Should print 1 printf("Digits in 1000: %d\n", countDigits(1000));// Should print 4 return 0; }
Key Explanations
unsigned intparameter: Since we're only dealing with non-negative numbers, using an unsigned integer ensures we don't accidentally pass negative values (though if you stick toint, it's okay as long as you only input non-negatives).- 0 check first: We handle
0immediately because the loop below won't run for0—if we skipped this,countwould stay0and return the wrong value. - Loop logic: For any number greater than 0, dividing by 10 removes the last digit (e.g.,
563 /10 = 56, then56/10=5, then5/10=0). Each time we do this, we increment our count. When the number becomes0, we stop and return the count.
Other Things to Check in Your Existing Code
- Did you initialize
countto0? If you set it to1by mistake, you'll get an extra digit (e.g.,563would return4instead of3). - Is your loop condition
num > 0? If you usednum >=0, the loop would run forever for0(since0/10is still0). - Are you returning the count correctly? Make sure you don't forget the
returnstatement at the end of the function.
Alternative (Using String Conversion)
If you're curious, another way to do this is converting the number to a string and checking its length. This is simpler but relies on C's standard library—great to learn later, but the loop method is better for understanding basic C logic:
#include <stdio.h> #include <string.h> int countDigits(int num) { if (num == 0) { return 1; } char num_str[20]; // Big enough to hold any integer's string representation sprintf(num_str, "%d", num); return strlen(num_str); }
Just compile and run the test code to see it work—play around with different inputs to make sure it handles all cases!
内容的提问来源于stack exchange,提问作者AndrewM

