我從The C Programming Language,Second Edition學習C語言。其中有以下代碼:C數組推,爲什麼減去'0'?
#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.我只是好奇它的1行:
++ndigit[c-'0'];
這會將數組的索引c加1,但爲什麼它會從c中減去0?當然,這沒有意義,對嗎?
''0''不是'0'。 – SLaks
這並非毫無意義。這是將字符數字轉換爲int的簡單方法。 – cnicutar
只需c將索引數組[48 57]。 c-'0'會將其降至[0 9]。 – tommyo