[英]What does it mean to subtract '0' from a variable in C?
void push(float[],float);
Here, st[]
is float data-type stack and exp[]
is char data-type array storing postfix expression.这里
st[]
是float数据类型的栈, exp[]
是char数据类型的数组,存放后缀表达式。
push(st,(float)(exp[i]-'0'));
I couldn't figure out the purpose of (exp[i]-'0')
section though.不过,我无法弄清楚
(exp[i]-'0')
部分的目的。 Why are we subtracting '0'
?为什么我们要减去
'0'
?
A character is basically nothing more than an integer, whose value is the encoding of the character.字符基本上无非是一个整数,其值是字符的编码。
In the most common encoding scheme, ASCII , the value for eg the character '0'
is 48
, and the value for eg '3'
is 51
.在最常见的编码方案ASCII中,字符
'0'
的值是48
,而字符'3'
的值是51
。 Now, if we have a variable someChar
containing the character '3'
and you do someChar - '0'
it's the same as doing 51 - 48
which will result in the value 3
.现在,如果我们有一个包含字符
'3'
的变量someChar
并且你执行someChar - '0'
它与执行51 - 48
相同,这将导致值3
。
So if you have a digit read as a character from somewhere, then you subtract '0'
to get the integer value of that digit.因此,如果您从某处读取一个数字作为字符,则减去
'0'
以获得该数字的整数值。
This also works on other encodings, not only ASCII, because the C specification says that all encodings must have the digits in consecutive order.这也适用于其他编码,不仅是 ASCII,因为 C 规范规定所有编码必须具有连续顺序的数字。
Note that this "trick" is not guaranteed to work for any non-digit character.请注意,此“技巧”不能保证对任何非数字字符都有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.