问题描述
我目前正在阅读Kernighan&的"The C Programming Language" Richie和我正在努力弄清生产线的功能.我想我只是有点愚蠢,还不太了解他们的解释.
I'm currently reading 'The C Programming Language' by Kernighan & Richie and I'm struggling to work out what a line does. I think I'm just being a little stupid, and not quite understanding their explanation.
++ndigit[c-'0'];
我不得不稍稍更改程序,就像以前ndigit
给我的垃圾值一样,所以我只是将数组实例化为0,而不是使用for循环遍历它,并以这种方式更改值.
I've had to change the program ever so slightly as ndigit
was previously giving me garbage values, so I just instantiate the array to 0, instead of traversing it with a for loop, and changing the values that way.
#include <stdio.h>
main()
{
int c, i, nwhite, nother;
int ndigit[10]= {0};
nwhite = nother = 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);
}
使用程序作为输入,我们将其打印到控制台-
Using the program as its input, we get this printed to the console -
digits = 7 2 0 0 0 0 0 0 0 1, white space = 104, other = 291
我了解7 2 0 0 0 0 0 0 0 1
是对输入中出现的单个数字出现0次出现7次,出现1次出现两次等的计数.)
I understand that 7 2 0 0 0 0 0 0 0 1
is a count of how many times the single numbers appear in the input 0 appears 7 times, 1 appears twice etc.)
但是,...[c-'0'];
的工作方式"如何?
But, how does the ...[c-'0'];
'work'?
推荐答案
您问以下表达式的工作原理
You asked how the below expression works
c-'0'
从ASCII码0中减去所输入字符的ASCII码,它定义了数组中必须存储计数的位置.
The ASCII code of the entered charecter is subtracted from the ASCII code of 0 and it defines the position in the array where the count has to be stored .
假设您从键盘输入 1 ,其中 1 的ASCII码为49,而 0 的ASCII码为48.因此
Suppose you enter 1 from the keyboard ASCII code for 1 is 49 and ASCII code for 0 is 48.hence
49-48 =1
,计数将存储在数组索引位置1中.
and the count will be stored in the array index location 1 .
这篇关于C数组计数(初学者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!