【问题标题】:C mathematical/integer operations on a char [duplicate]char上的C数学/整数运算[重复]
【发布时间】: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


【解决方案1】:

字符数字,但'0' 不是 0,但(在大多数情况下)48'1' 不是 em> 1 但(在大多数情况下)49,等等。

Here is the detailed explanation of it.

【讨论】:

    猜你喜欢
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多