【发布时间】: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>= '0' && c<= '9') ) 是必要的,它会检查 c 是否为数字。另外,我不明白为什么[c-'0'] 会在从字符串转换('0')中减去输入变量(c)时检查输入(c)是否为数字。
任何建议/解释将不胜感激。
提前谢谢:)
【问题讨论】:
-
要么你误读了 K&R,要么他们有错误。我阅读代码的方式是,如果 c 是数字,则递增 ndigit 的相应值。因此,例如如果 c == '7',则 c-'0' = '7'-'0' = 7(因为数字的字符编码是连续的),因此代码将增加 digit[7]。
-
Michael L,把它作为答案。 @jimmcnamara 这个练习的重点是自己编写 isdigit 函数。
-
如果您满意,请将其中一个答案标记为已接受