【发布时间】:2014-02-07 00:54:17
【问题描述】:
我正在从 The C Programming Language, Second Edition 学习 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);
}
现在,我可以理解这段代码在做什么了。它是计算每个数字在输入中出现的次数,然后将该计数放入数字的索引中,即 11123 = 0 3 1 1 0 0 0 0。我只是对其中的一行感到好奇:
++ndigit[c-'0'];
这会将数组的索引 c 加 1,但是为什么它会从 c 中减去 0?这肯定是没有意义的,对吧?
【问题讨论】:
-
这不是没有意义的。这是一种将字符数字转换为 int 的简单方法。
-
只是 c 将在 [48 57] 处索引数组。 c-'0' 会将其降至 [0 9]。