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

C语言switch-case计数程序异常:数字0-4被统计为其他字符

问题分析:输入数字0-4被统计为其他字符的原因

嘿,我明白你碰到的麻烦了——不管输入0-4还是别的字符,全被归到“其他字符”里统计了对吧?咱们来拆解下问题根源,再给你修复方案。

首先贴出你的代码方便参考:

int main() { 
    int a; 
    int num_0 = 0; 
    int num_1 = 0; 
    int num_2 = 0; 
    int num_3 = 0; 
    int num_4 = 0; 
    int num_other = 0; 
    printf("Input something\n"); 
    while ((a = getchar()) != EOF) { 
        switch (a) { 
            case 0: num_0++;break; 
            case 1: num_1++;break; 
            case 2: num_2++;break; 
            case 3: num_3++;break; 
            case 4: num_4++;break; 
            default: num_other++;break; 
        }; 
    } 
    printf("0 has been typed %d", num_0);printf(" times\n"); 
    printf("1 has been typed %d", num_1);printf(" times\n"); 
    printf("2 has been typed %d", num_2);printf(" times\n"); 
    printf("3 has been typed %d", num_3);printf(" times\n"); 
    printf("4 has been typed %d", num_4);printf(" times\n"); 
    printf("other characters have been typed %d", num_other);printf(" times\n"); 
    return 0; 
}

问题核心:混淆了字符ASCII值与整数本身

当你从键盘输入字符0的时候,getchar()读取到的并不是整数0,而是这个字符对应的ASCII码值48;同理:

  • 字符1对应ASCII码49
  • 字符2对应ASCII码50
  • 字符3对应ASCII码51
  • 字符4对应ASCII码52

你的switch分支里写的case 0、case 1等是整数0-4,和输入字符的ASCII码完全不匹配,所以所有输入都会走到default分支,被统计为“其他字符”。

修复方案

把case后面的数字改成字符常量形式(用单引号括起来),这样就能精准匹配输入的字符了。修改后的switch部分如下:

switch (a) { 
    case '0': num_0++; break; 
    case '1': num_1++; break; 
    case '2': num_2++; break; 
    case '3': num_3++; break; 
    case '4': num_4++; break; 
    default: num_other++; break; 
}

另外补充个小提示:要结束输入并让程序输出统计结果,Windows系统按Ctrl+Z,Linux/macOS系统按Ctrl+D就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:58:21