单引号vs无引号 [英] single quote vs no quote in C
问题描述
在以下代码中:
#include< stdio.h>
/ *计数数字,空格,其他* /
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 =='\\\
'|| c =='\t')
++ nwhite;
else
++ nother
printf(digits =);
for(i = 0; i <10; ++ i)
printf(%d,ndigit [i]);
printf(,white space =%d,other =%d\\\
,
nwhite,nother);
}
我不明白为什么要替换这一行:
if(c> ='0'&& c< ='9')
if(c> ; = 0&& c <= 9)
给出不同的结果?例如,当代码用后面的选项写入并且用户按下9按钮时,程序不将它看作一个数字,而是看作其他。
解决方案表达式
'0'
是字符文字。它的确切值取决于系统上使用的编码,但在最常见的编码方案(ASCII)中,我们可以检查。 此表,并看到其值为48 code> decimal。
另一个表达式
0
是一个整数字符, code> 0 。
0 =='0'
与执行0 == 48
是一样的。 >in the following code:
#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); }
I don't understand why replacing this line:
if (c >= '0' && c <= '9')
with this line:
if (c >= 0 && c <= 9)
give different results? For example, when the code is written with the latter option and the user press the 9 button, the program see it not as a digit, but as "other".
解决方案The expression
'0'
is a character literal. Its exact value depends on the encoding used on your system, but in the most common encoding scheme (ASCII) we can check e.g. this table and see that its value is48
decimal.The expression
0
on the other is an integer literal and has the value0
.Doing e.g.
0 == '0'
is the same as doing0 == 48
which is definitely not true.这篇关于单引号vs无引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!