简单数据类型和输出格式符
类型说明符 |
格式符 |
char |
%c |
short int |
%hd, %hi, %hx, %ho |
unsigned short int |
%hu, %hx, %ho |
int |
%d, %i, %x, %o |
unsigned int |
%u, %x, %o |
long int |
%ld, %li, %lx, %lo |
unsigned long int |
%lu, %lx, %lo |
long long int |
%lld, %lli, %llx, %llo |
unsigned long long int |
%llu, %llx, %llo |
float |
%f, %e, %g, %a |
double |
%f, %e, %g, %a |
long double |
%Lf, %Le, %Lg |
* |
%p |
数据类型的隐式转换
编译器按下面的顺序进行自动类型转换:
1.如果其中一个数是long double类型的,那么另一个操作数被转换为long double类型,计算的结果也是long double类型。
2.如果一个数是double类型的,那么另一个操作数被转换为double类型,计算的结果也是double类型。
3.如果一个数是float类型的,那么另一个操作数被转换为float类型,计算的结果也是float类型。
4.如果一个数是Bool、char、short int、bit field、枚举类型的,则全部转换为int类型,计算的结果也是int类型。
5.如果一个数是long long int类型的,那么另一个操作数被转换为long long int类型,计算的结果也是long long int类型。
6.如果一个数是long int类型的,那么另一个操作数被转换为long int类型,计算的结果也是long int类型。
整型数运算遵循一个规则:字节小的往字节大的转,有符号的往无符号的转
所有比int型小的数据类型(包括char,unsigned char,short,unsigned short)转换为int型再参与运算。如果转换后的数据会超出int型所能表示的范围的话,则转换为unsigned int型。
一般来说这样提升,从小到大:比int小的 -> int -> unsigned int -> long -> unsigned long
eg:(测试环境Mac)
char c = 'c';
unsigned short b = 1;
b + c; // 结果为int类型
unsigned short a;
unsigned short b;
a+b; // 结果为int类型
enum会跟据最大值来决定类型,一般来说为int型,如果超出int型所能表示的范围,则用比int型大的最小类型来表示(unsigned int, long 或者unsigned long)
enum e {MON = 12345678987654321};
enum e eg = MON; // 此时eg为unsigned long类型
int i;
eg + i; // 结果为unsigned long类型
如果表达式中混有unsigned short和int型时,如果int型数据可以表示所有的unsigned short型的话,则将unsigned short类型的数据转换为int型,否则,unsigned short类型及int型都转换为unsigned int类型。unsigned int和long同理。
几个常用的数据类型转换
double — float
|
long
|
unsigned
|
int — char,short
signed和unsigned之间:http://blog.sina.com.cn/s/blog_590be5290100htvu.html