在c ++中的减法 [英] Char Subtraction in c++
问题描述
我已经有了这个代码。
char x ='2';
x - ='0';
if(x)cout<< 多于零< endl
这返回了多于零作为输出,所以知道xi的值尝试这个代码。
char x ='2';
x - ='0';
if(x)cout<< x<< endl
我得到一个空字符(或换行符)作为输出。
$ b $根据C ++标准(2.3个字符集)
- ...在源和执行基本字符集中,
上面的十进制数字列表中的0之后的每个字符应为
,大于上一个值。
因此,任何字符集中相邻数字的代码都相差1。
因此,在此代码片段
char x ='2';
x - ='0';
if(x)cout<< x<< endl
'2'
code>'0'(代表这些字符的代码之间的区别;例如在ASCII中,这些代码是0x32和0x30,而在EBCDIC中它们分别是0xF2和0xF0)等于 2
您可以通过以下方式检查这一点
if(x)cout < (int)x < endl
或
if(x)cout < static_cast< int>(x)< endl
如果你只是写
if(x)cout < x<< endl
那么运算符<尝试输出 x
作为值 2
的可打印字符图像,因为 x
的类型为 char
。
I am fairly new to C++ and i have some trouble in understanding character subtraction in c++.
I had this code intially
char x='2';
x-='0';
if(x) cout << "More than Zero" << endl;
This returned More than Zero as output so to know the value of x i tried this code.
char x='2';
x-='0';
if(x) cout << x << endl;
And i am getting null character(or new line) as output.
Any help is appreciated.
According to the C++ Standard (2.3 Character sets)
- ...In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
So the codes of adjacent digits in any character set differ by 1.
Thus in this code snippet
char x='2';
x-='0';
if(x) cout << x << endl;
the difference between '2'
and '0'
(the difference between codes that represent these characters; for example in ASCII these codes are 0x32 and 0x30 while in EBCDIC they are 0xF2 and 0xF0 correspondingly) is equal to 2
.
You can check this for example the following way
if(x) cout << ( int )x << endl;
or
if(x) cout << static_cast<int>( x ) << endl;
If you just write
if(x) cout << x << endl;
then the operator << tries to output x
as a printable character image of the value 2
because x
is of type char
.
这篇关于在c ++中的减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!