您的位置:程序门 -> c/c++ ->



我想问一个关于数组下标计算的问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


我想问一个关于数组下标计算的问题
发表于:2007-05-25 10:31:45 楼主
...let   is   write   a   program   to   count   the   number   of   occurrences   of   each   digit,   of   white   space   characters   (blank,   tab,   newline),   and   of   all   other   characters....

#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);
      }


我的问题是   ++ndigit[c- '0 '];为什么不能替换为   ++ndigit[c-0];或   ++ndigit[c];   我觉得c- '0 '的值是int,c也是int,所以c-0   =   c   =   c- '0 ',可是这时错的,我不太明白,望达人解惑。


发表于:2007-05-25 11:01:241楼 得分:0
字符 '0 '是整数0x30,不是整数0
发表于:2007-05-25 11:02:112楼 得分:0
自己先查看ansi字符表
发表于:2007-05-25 12:01:283楼 得分:0
先谢谢yoyo_alex_lw()   ,尽管还不是很明白。

继续小白问题-0-

1   字符 '0 '和整数0   在计算机中为什么不一样?

2   ++ndigit[c-0x30];程序正常,++ndigit[c-48];程序也正常,而在++ndigit[c-00110000];程序错误,为什么十进制,十六进制都ok,到二进制就不行了呢?

3   ++ndigit[c- '0 '];为什么不能替换为     ++ndigit[c];   决的后面的更高效?
发表于:2007-05-25 12:52:144楼 得分:0
首先c必须定义为char类型,才有你下面的操作!
然后数字和字符在内存中的存放是不一样的!字符 '0 '代表的是ascii值48,那这个时候,比如说你输入一个字符 '1 ',它的值是49,则必须49-48=1,如果变成c-0,就是49-0=49
发表于:2007-05-25 14:23:155楼 得分:0
谢谢littterzhao()   的解释,可是我还是有点茫然:p
发表于:2007-05-25 14:26:456楼 得分:0
感觉the   c   programming   language
by   brian   w.   kernighan   and   dennis   m.   ritchie.这书有点难
发表于:2007-05-25 17:03:107楼 得分:0
整数0   其实就是对应ascii中的nul   ascii码:0000000(十进制为0)
字符0   ascii:0110000(十进制为48)
发表于:2007-05-28 11:39:428楼 得分:0
谢谢jinwei1984()
发表于:2007-05-28 12:23:589楼 得分:0
++ndigit[c-00110000];
====================
c/c++的编译器不支持在代码中直接写二进制.
发表于:2007-05-29 14:01:1110楼 得分:0
又学到新东西了(c/c++的编译器不支持在代码中直接写二进制),谢谢a_b_c_abc(黄瓜@youcandoit)


快速检索

最新资讯
热门点击