我正在从 K&R 书中学习 C,我偶然发现了代码来计算编号。空白字符(空白、制表符、换行符)和所有其他字符的出现次数。
代码是这样的:
#include <stdio.h>
/* count digits, white space, others */
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",
nwhite, nother);
}
我需要问两个问题..
第一个问题:
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
我很清楚'0'和'9'分别代表ASCII值0和9。但我似乎不明白的是为什么我们甚至需要使用 ASCII 值而不是整数本身。就像我们为什么不能简单地使用
if (c >= 0 && c <= 9)
判断 c 是否在 0 到 9 之间?
第二个问题:
++ndigit[c-'0']
上面的语句有什么作用?
为什么我们不在这里采用 c 的 ASCII 值?
因为如果我们这样做,它应该写成['c'-'0']
。
最佳答案
1.
C 是一个字符,而不是一个整数。因此我们需要将它们与 ASCII 值进行比较。整数 0 和 9 对应于 Nul
和 Tab
,不是我们要找的东西。
2.
通过减去 ASCII 值,与整数对应的索引会增加。例如,如果我们的号码是'1'
。然后 '1' - '0' = 1
因此索引增加为 1,这是跟踪字符的便捷方法。我们不放置 ['c' - '0']
因为我们关心变量 c
而不是字符 'c'
此表显示了字符的表示方式,它们与整数不同。主要收获是 '1' != 1
http://www.asciitable.com/
关于c - '<letter>'的语法和不同含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48879445/