类型自动转换
- 例如一个char型变量a,其值为-1,另一个unsigned char型变量b,将变量a的值赋给变量b,则变量b的值为255
char a;
unsigned char b;
a = -1;
b = a;
printf("b=%d\n",b);
- 一个unsigned char变量a,其值为255,分别赋值给char型变量b,int型变量c,则赋值后变量b为-1,变量c为255
unsigned char a;
char b;
int c;
a = 255;
b = a;
c = a;
printf("b=%d,c=%d\r\n",b,c);
- 一个char型变量a,其值为-1,分别赋值给short变量b和unsigend short 变量c,则赋值后b的值为-1,c的值为65535
char a;
short b;
unsigned short c;
a = -1;
b = a;
c = a;
printf("b=%d,c=%d\r\n",b,c);
- 一个unsgined short型变量a,其值为0x6587,分别赋值给unsinghed char变量b和变量c,则赋值后b的值为0x87,c的值为0xffffff87
unsigned short a;
unsigned char b;
char c;
a = 0x6587;
b = a;
c = (unsigned long)a;
printf("b=0x%x,c=0x%x\r\n",b,c);
- 一个int型变量a,其值为-1,另一个unsigned int变量为b,其值为39,将变量a乘以100再除以变量b的值赋给int变量c,则c的值为110127364
int a;
unsigned int b;
int c;
a = -1;
b = 39;
c = a * 100 / b;
printf("c=%d\r\n",c);
- 如果将上述的变量b的值使用常量39代替,则c的值为-2
int a;
int c;
a = -1;
c = a * 100 / 39;
printf("c=%d\r\n",c);
- 如果将上述使用的常量改成39u,则c的值为110127364
int a;
int c;
a = -1;
c = a * 100 / 39u;
printf("c=%d\r\n",c);
- 一个int型变量a,其值为-1,另一个unsigned int变量为b,其值为39,将变量a乘以100再除以强制转换变量b为int类型后的值赋给int变量c,则c的值为-2
int a;
unsigned int b;
int c;
a = -1;
b = 39;
c = a * 100 / (int)b;
printf("c=%d\r\n",c);