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

C语言如何统计数字最后一个非零数位之后的零的个数

需求说明

统计一个整数最后一个非零数位之后的零的数量,例如输入20400,输出2。

现有代码问题

你当前提供的C代码实现的是计算输入整数阶乘的最后一位非零数值,和你要实现的统计末尾零数量的需求不匹配。

正确实现

逻辑说明

  • 对输入的整数循环判断末位是否为0
  • 每识别到末位为0,计数加1,同时将原数除以10去掉末尾的0
  • 末位不为0时终止循环,返回计数值即可

代码示例

#include<stdio.h>

int countTrailingZeros(int n) {
    int count = 0;
    // 兼容负数输入,末尾零数量和正负无关
    if (n < 0) n = -n;
    while (n != 0 && n % 10 == 0) {
        count++;
        n /= 10;
    }
    return count;
}

int main() {
    int inputNum;
    scanf("%d", &inputNum);
    printf("%d\n", countTrailingZeros(inputNum));
    return 0;
}

测试验证

输入20400,代码执行后输出2,符合需求。

内容的提问来源于stack exchange,提问作者kylie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:12:04