【问题标题】:Confused with subscript expression in array与数组中的下标表达式混淆
【发布时间】:2021-12-27 05:53:29
【问题描述】:

我正在尝试查找输入中数字的出现次数(键入的数字)。我对表达式 ++ndigit[ c - '0'] 中数组的下标表达式感到困惑。

这里是代码

#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()) I= EOF) 

        {if (C >= '0' && C <= '9') 

           {++ndigit[c-'0'];}
       /*here i stucked explain me how 
            subscript 
          expression going too work*/

       elseif (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);
    }

【问题讨论】:

  • 首先,你的代码中有很多格式和语法问题。是这个问题,还是逻辑本身?
  • while ((c = getchar()) I= EOF) ???

标签: arrays c expression subscript


【解决方案1】:

char 只是一个 7 位数字。计算机使用计算机使用的任何字符编码(主要是 ASCII)将这些数字编码为字符。

在 ASCII 中,0 的值为 481 的值为 49,...,9 的值为 57

所以:

If c is 48 (or '0'), c - '0' = 48 - 48 = 0, ndigit[c - '0'] = ndigit[0]
If c is 49 (or '1'), c - '0' = 49 - 48 = 1, ndigit[c - '0'] = ndigit[1]

...
If c is 58 (or '9'), c - '0' = 57 - 48 = 9, ndigit[c - '0'] = ndigit[9]

所以这是一种将 ASCII 数字值映射到数字值的方法。而++ 只是增量。所以:如果ndigit[0] = 0; ++ndigit[0] 那么ndigit[0] = 1

【讨论】:

  • char 至少为 8 位,C 实现通常支持的不仅仅是 7 位 ASCII 码,并且在此答案中无需提及 ASCII,因为 ndigit[c - '0'] 仅基于关于 C 标准中的规范;它不需要 ASCII。
猜你喜欢
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2023-03-08
  • 2018-09-11
  • 2018-07-05
相关资源
最近更新 更多