【问题标题】:Check whether the input is digit or not in C programming在C编程中检查输入是否为数字
【发布时间】:2015-06-01 02:19:20
【问题描述】:

我目前正在阅读这本书:The C Programming Language - By Kernighan and Ritchie (second Edition) 和其中一个示例,我无法理解如何检查输入是否为数字。示例在第 22 页,在数组章节下进行了解释。

下面是例子。

#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']这行检查c中的输入字符是否为数字。但是,我认为只有 if 语句 ( if (c&gt;= '0' &amp;&amp; c&lt;= '9') ) 是必要的,它会检查 c 是否为数字。另外,我不明白为什么[c-'0'] 会在从字符串转换('0')中减去输入变量(c)时检查输入(c)是否为数字。

任何建议/解释将不胜感激。

提前谢谢:)

【问题讨论】:

  • 要么你误读了 K&R,要么他们有错误。我阅读代码的方式是,如果 c 是数字,则递增 ndigit 的相应值。因此,例如如果 c == '7',则 c-'0' = '7'-'0' = 7(因为数字的字符编码是连续的),因此代码将增加 digit[7]。
  • Michael L,把它作为答案。 @jimmcnamara 这个练习的重点是自己编写 isdigit 函数。
  • 如果您满意,请将其中一个答案标记为已接受

标签: c arrays digit


【解决方案1】:

if 语句检查字符是否为数字,++ndigit[c-'0'] 语句更新该数字的计数。当c 是介于'0''9' 之间的字符时,则c-'0' 是介于09 之间的数字。换句话说,'0' 的 ASCII 值是十进制的 48,'1' 是 49,'2' 是 50,等等。所以c-'0'c-48 相同,并将48,49,50,... 转换为@ 987654335@

提高理解的一种方法是在代码中添加printf,例如替换

if (c >= '0' && c <= '9')
     ++ndigit[c-'0'];

if (c >= '0' && c <= '9')
{
    ++ndigit[c-'0'];
    printf( "is digit '%c'   ASCII=%d   array_index=%d\n", c, c, c-'0' );
}

【讨论】:

    【解决方案2】:

    我会试着用一个例子来解释

    假设输入是 abc12323

    所以1=1的频率

    2=2的频率

    3=2 的频率

    if (c >= '0' && c <= '9') //checks whether c is a  digit  
          ++ndigit[c-'0']; 
    

    现在如果你执行 printf("%d",c) 那么你会得到 ​​p>

    字符

    对于 c='0',ascii 值将是 48,c='1' ascii 值将是 49,它会继续

    c='9' 直到 57。

    在您的程序中,您要保持输入中数字的频率,因此您需要在每次获取时更新数组中数字的索引

    如果你执行 ndigit[c]++ 那么它将更新 ndigit[48] for c='0',ndigit[49] for c='1'

    因此,您可以将 ndigit[c-'0']++ 作为 '0'=48 的 ascii 值(十进制)

    或者你可以简单地做 ndigit[c-48]++ 所以对于 c='0' ndigit[0] 被更新,c=1'

    ndigit[1] 已更新

    你可以在这里查看重构代码http://ideone.com/nWZxL1

    希望对你有帮助,祝你编程愉快

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2013-07-25
      • 2023-03-27
      • 2014-03-15
      • 2015-05-11
      相关资源
      最近更新 更多