3.3 dec、hex和oct
cout Monsieur cuts a striking figure!\n
cout chest = chest (42 in decimal)\n
cout waist = waist (0x42 in hex)\n
cout inseam = inseam (042 in octal)\n
return 0;
}
1. 编译输出:
Monsieur cuts a striking figure! chest = 42 (42 in decimal) waist = 66 (0x42 in hex) inseam = 34 (042 in octal)
2. 代码详解:
整数字面值
整数字面值是显式地书写的常量,如212或2334。
C++三种描述整数的方式:基数为10、基数为8和基数为16。
使用前一或两位来标识数字常量的基数。如果第一位为1~9,则基数为10(十进制)。如果第一位是0,第二位是1~7,则基数为8(八进制)。如果前两位为0x或0X,则基数为16(十六进制)。
C++默认情况下,cout以十进制格式显示整数,而不管这些整数在程序中是如何书写的。
不管把值书写为10、012还是0xA,都以相同的方式存储在计算机中——被存储为二进制数(以2为基数)。
hexoct2.cpp: display values in hex and octal
#include iostream int main() using namespace std; int chest = 42; int waist = 42; int inseam = 42; cout Monsieur cuts a striking figure! endl; cout chest = chest (decimal for 42) endl; cout hex; cout waist = waist (hexadecimal for 42) endl; cout oct; cout inseam = inseam (octal for 42) endl; return 0; }
1. 编译输出:
Monsieur cuts a striking figure! chest = 42 (decimal for 42) waist = 2a (hexadecimal for 42) inseam = 52 (octal for 42)
2. 代码详解:
头文件iostream提供了控制符dec、hex和oct,分别用于指示cout以十进制、十六进制和八进制格式显示整数。
cout hex; 和 cout oct; 代码不会在屏幕上显示任何内容,而只是修改cout显示整数的方式。
由于标识符hex位于名称空间std中,而程序使用了该名称空间,因此不能将hex用作变量名。
扩展:C++如何确定常量的类型
默认情况下,C++将整型常量存储为int类型。
后缀表示类型,是放在数字常量后面的字母。l或L后缀表示long常量,u或U后缀表示unsigned int常量,ul后缀表示unsigned long常量,ll或LL后缀表示long long常量,ull后缀表示unsigned long long常量。
0条评论