You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完善统计非负整数位数的C语言函数,使程序正常运行?

How to Write a C Function to Count Digits in a Non-Negative Integer

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 int parameter: 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 to int, it's okay as long as you only input non-negatives).
  • 0 check first: We handle 0 immediately because the loop below won't run for 0—if we skipped this, count would stay 0 and return the wrong value.
  • Loop logic: For any number greater than 0, dividing by 10 removes the last digit (e.g., 563 /10 = 56, then 56/10=5, then 5/10=0). Each time we do this, we increment our count. When the number becomes 0, we stop and return the count.

Other Things to Check in Your Existing Code

  • Did you initialize count to 0? If you set it to 1 by mistake, you'll get an extra digit (e.g., 563 would return 4 instead of 3).
  • Is your loop condition num > 0? If you used num >=0, the loop would run forever for 0 (since 0/10 is still 0).
  • Are you returning the count correctly? Make sure you don't forget the return statement 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:39:23