语法和“< letter>”的不同含义 [英] Syntax and different meanings of '<letter>'

查看:65
本文介绍了语法和“< letter>”的不同含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从K& R书中学习C,并且碰到了代码以计算否。空格字符(空白,制表符,换行符)和所有其他字符的出现。

代码如下:

I am learning C from the K&R book and I came across the code to count the no. of occurrence of white space characters (blank, tab, newline) and of all other characters.
The code is like this:

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

我需要问2个问题。.

1st问题:

I need to ask 2 questions..
1st question:

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

我很清楚, 0和 9表示ASCII值0& 9个。但是我似乎不明白的是,为什么我们甚至需要使用ASCII谷值而不是整数本身。就像为什么我们不能简单地使用

I very well know that '0' and '9'represents the ASCII value of 0 & 9 respectively. But what I don't seem to understand is why we even need to use the ASCII vale and not the integer itself. Like why can't we simply use

if (c >= 0 && c <= 9)

查找c是否在0到9之间?

to find if c lies between 0 and 9?

第二个问题:

++ndigit[c-'0']

上面的语句是做什么的?

为什么我们不在这里取c的ASCII值?

因为如果这样做,它应该被写为 ['c'-'0']

What does the above statement do?
Why aren't we taking the ASCII value of c here?
Because if we did, it should have been written as ['c'-'0'].

推荐答案


  1. getchar()返回字符代码和标记值(EOF)。因此,我们知道 c 在循环内保存了字符代码。

  1. getchar() returns character codes and sentinel values (EOF). So, we know c holds a character code inside the loop.

c-'0'是字符代码数字行上从c值(字符代码)到 0代码的距离。根据C标准,字符代码必须以连续的顺序'0','1,'2','3','4','5','6','7','8', '9'。因此,该表达式将计算数字字符的整数值。

c-'0' is the distance on the character code "number line" from the value of c (a character code) to the code for '0'. Per the C standard, character codes must have these digits in consecutive order '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. So, the expression computes the integer value of the digit character.

这篇关于语法和“&lt; letter&gt;”的不同含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆