【问题标题】:C array push, why subtract '0'?C数组推送,为什么要减去'0'?
【发布时间】: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]。

标签: c arrays


【解决方案1】:

表达式c - '0' 正在从数字的字符表示转换为同一数字的实际整数值。例如,它将 char '1' 转换为 int 1

我认为在这里查看完整示例更有意义

int charToInt(char c) { 
  return c - '0';
}

charToInt('4') // returns 4
charToInt('9') // returns 9 

【讨论】:

  • 啊,我明白了。当你这样说时,似乎有点明显。谢谢老哥!
【解决方案2】:

它不是减去零...它是减去字符“0”的 ASCII 值。

这样做会给你一个数字的序数值,而不是它的 ASCII 表示。换句话说,它将字符 '0' 到 '9' 分别转换为数字 0 到 9。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2011-02-03
    • 2021-02-01
    • 2020-08-12
    相关资源
    最近更新 更多