c - 使用 switch-case 结构来计算数字被输入的次数

标签 c character-encoding

创建一个 C 程序来计算每个数字 0-4 被键入的次数。使用 switch-case 结构。使用 default 来计算其他字符的数量。打印特定数字的输入次数。

这是我的代码:

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;
}

无论我输入什么,包括0,1,2,3,4在内的所有数字都被算作其他字符。有人可以告诉我为什么我的代码不起作用。

最佳答案

switch (a) 将比较 a 的代码。如果您输入数字,则应该是;

    case '0':
        num_0++;break;
    case '1':
        num_1++;break;
  ...

切换字符值而不是整数(0的int值不是0,例如在ASCII中它是48,但我们不直接使用该值,所以它是完全便携)

也许更好的做法是创建一个表:

int count[10] = {0};

....
a -= '0';  // removes the offset
if ((a >= 0) && (a < 10))  // check bounds
{
    count[a]++;
}

关于c - 使用 switch-case 结构来计算数字被输入的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48379589/

相关文章:

c - cl : array type has incomplete element type => why warning and not error?

Python Thrift 二进制类型需要编码?

javascript - 不兼容的字符编码 : ASCII-8BIT and UTF-8 while using javascript in rails

c++ - 如何将 unicode QString 转换为 std::string?

c - 在 emacs 中将 openmp 指令缩进为 C/C++ 代码

c++ - atoi(string.c_str()) 偶尔出现未处理的异常已更新

c - 使用互斥锁来控制 while 循环的时序

c - 为什么这个简单的代码有时不起作用????然后当我重新启动我的代码块时它有时会起作用

php页面不显示阿拉伯文字

php - 字符编码问题