为什么“else if”语句不起作用以及 ndigit[c-'0'] 的含义是什么?

问题描述

我是 C 的初学者,我不理解书中的这个例子“The C Programming Language by Brian W. Kernighan,Dennis M. Ritchie”

此程序计算“从 0 到 9 的每个数字”、“空格”和“其他字符

#include <stdio.h>

/*count digits,white space,others */
int main()
{
    int c,i,nwhite,nother;
    int ndigit[10];

    nwhite = nother = 0;
    for (i = 0; i < 10; i++)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
        if (c >= '0' || c <= '9')
            ++ndigit[c-'0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;

    printf("digits =");
    for (i = 0; i < 10; ++i)
        printf(" %d",ndigit[i]);
    printf(",white space = %d,other = %d\n",nother);
}

根据这本书,这个程序的输出应该是这样的:

数字 = 9 3 0 0 0 0 0 0 0 1,空格 = 123,其他 = 345

但是当我运行它时,它是这样的:

数字 = 9 3 0 0 0 0 0 0 0 1,空格 = 2,其他 = 18

问题 1:为什么 ndigit[c-'0'] 中有一个 0?我不明白它的作用。

问题 2:为什么我的“else if”和“else”语句不能正常工作?他们没有得到正确的数字。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)