【发布时间】:2017-05-16 14:47:12
【问题描述】:
我目前正在阅读 K&R 书籍。第 22 页,数组 1.6
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 语句中删除“0”。但是,阵列停止工作。如果chars被认为是整数,为什么程序正常运行需要'0'
【问题讨论】:
-
0不是'0' -
c-'0'是从 ASCII 数字中获取数字的简写方式。由于 '0' 是最低的 ASCII 值,并且数字在 ASCII 编码中是连续的,所以从数字字符中减去'0'会得到它的值。 -
字符 '0'(零)的 ASCII 值为 48,与 NUL 字符 '\0' 不同,后者的数值为 0。注意:C 不受 ASCII 标准的约束但如果你使用的电脑不应该告诉你。
-
@DanAllen 他减去了“0”,这样作为输入的字符实际上代表了它们显示的数字。
-
@AppWriter 但这不是重点吗? Grayson 不知道为什么这段代码(可能不是他们的)需要从某些东西中减去“0”并认为它什么也没做,因为他们认为“0”是零。
标签: c