gpt4 book ai didi

c - 为什么我们需要 "-' 0'"来修改数组?

转载 作者:行者123 更新时间:2023-11-30 18:20:01 26 4
gpt4 key购买 nike

这是 Dennis Ritchie 的 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);
}

为什么这一行需要 -'0'

++ndigit[c-'0'];

如果我将其更改为++ndigit[c],程序将无法正常运行。为什么我们不能直接写++ndigit[c]

我已经看过书上的解释,但我不明白。

This works only if '0', '1', ..., '9' have consecutive increasing values. Fortunately, this is true for all character sets. By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions. This is natural and convenient; for example c-'0' is an integer expression with a value between 0 and 9 corresponding to the character '0' to '9' stored in c, and thus a valid subscript for the array ndigit

最佳答案

要了解为什么我们需要“-'0'”,您首先需要了解 ASCII 表 - http://www.asciitable.com/

现在您需要了解 C 中的每个字符都由 0 到 127 之间的数字表示(扩展为 255)。

例如,如果您要打印字符“0”作为其数值:

printf( "%d", '0' );

output: 48

现在您已经声明了一个大小为 10 - ndigit[ 10 ] 的数组,其中n单元格代表数字n的次数被作为输入给出。

因此,如果您收到“0”作为输入,您会想要执行 ndigit[ 0 ]++所以你需要从 char 转换为整数。你可以通过减去 48 ( = '0' ) 来做到这一点

这就是为什么我们使用 ++ndigit[c-'0'];

如果 c = '5',我们将得到

++ndigit['5' - '0']

++ndigit[ 53 - 48 ]

++ndigit[ 5 ]

正如我们所希望的那样

关于c - 为什么我们需要 "-' 0'"来修改数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com