[英]Printing a character data type as integer data type
#include<stdio.h>
main()
{
char a[12];
scanf("%s",a);
int s=0;
s=s+a[1];
printf("%d",s);
}
example:
a=1234
output:50
This is a basic c program.When i try to print the value of s,it displays 50 but when i replace a[1]
with a[1]-'0'
,it displays the exact value of character present at the index (output: 2)
.Any reason why is it happening ? 这是一个基本的c程序。当我尝试打印s的值时,它将显示50,但是当我将a[1]
替换a[1]
a[1]-'0'
,它将显示索引处出现的字符的确切值(output: 2)
。为什么会这样?
Character constant '2'
in the ASCII table has code 50. So using the format specifier %d
the character is displayed as an integer that is its value 50 is displayed. ASCII表中的字符常量'2'
的代码为50。因此,使用格式说明符%d
将字符显示为整数,并显示其值50。
As for this expression 至于这个表情
a[1] - '0'
then as it has been said a[1]
that represents the character '2'
stores the ASCII value 50
. 然后,正如已经说过a[1]
,代表字符'2'
a[1]
存储ASCII值50
。 The character '0'
has the ASCII code 48
. 字符'0'
具有ASCII码48
。 So the difference yieds 2
. 因此,差异就大了2
。
lets take a look what happened at run time. 让我们看看运行时发生了什么。
s is initialized to 0
and a[] is scanned with "1234";
which is 这是
a[0] = '1';
a[1] = '2';
a[2] = '3';
a[3] = '4';
first case 第一种情况
s=s+a[1]; // 0 + asci value of 2 which evaluates to 50
second case 第二种情况
s=s+a[1]-'0' // 0 + asci value of 2 i.e 50 - asci value of 0 i.e 48 = 2
C specifies that the codes for characters '0'
, '1'
, '2'
, ... '9'
are sequential. C指定字符'0'
, '1'
, '2'
,... '9'
是连续的。
'0' + 3
must equal '3'
. '0' + 3
必须等于'3'
。
This applies for any character set: the common ASCII or others. 这适用于任何字符集:通用ASCII或其他。
Subtraction from '0'
yields the numeric difference. 减去'0'
产生数值差。
printf("%d",'2' - '0'); // must print 2
... the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. ...在上述十进制数字列表中,0后的每个字符的值应比前一个的值大一个。 ... C11dr §5.2.1 3 ... C11dr§5.2.13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.