C語言 學習之 數據類型默認轉換

默認情況下編譯情況的互轉

詳細可參考其它博文

有無符號 整數相除,得到的結果如下

int / int = int
uint/int = uint	int/uint = uint	uint/uint = uint
有符號的整數除以有符號整數 最後的結果是有符號的, 其他的情況下得到的結果都是無符號的整數
unsigned int num2 = 0x80000000, temp2 = 10000;

printf("int/int = %d / %d = %d\r\n", num1,temp1, num1/temp1);
printf("int/uint = %d / %d = %d\r\n", num1,temp2, num1/temp2);
printf("uint/int = %d / %d = %d\r\n", num2,temp1, num2/temp1);
printf("uint/uint = %d / %d = %d\r\n", num2,temp2, num2/temp2);
int/int = -2147483648 / 1000 = -2147483
int/uint = -2147483648 / 1000 = 2147483
uint/int = -2147483648 / 1000 = 2147483
uint/uint = -2147483648 / 1000 = 2147483

int 類型轉short 類型

精度丟失,如果有效值超過16位,會導致結果不可預測
int num1 = 0x80000000, temp1 = 1000;
unsigned int num2 = 0x80000000, temp2 = 1000;

short num = num1/temp1;
printf("int to short = %d\r\n", num);
num = num2/temp2;
printf("uint to short = %d\r\n", num);

printf("int/int = %d / %d = %d\r\n", num1,temp1, num1/temp1);
printf("int/uint = %d / %d = %d\r\n", num1,temp2, num1/temp2);
printf("uint/int = %d / %d = %d\r\n", num2,temp1, num2/temp1);
printf("uint/uint = %d / %d = %d\r\n", num2,temp2, num2/temp2);
int to short = 15205
uint to short = -15205
int/int = -2147483648 / 1000 = -2147483
int/uint = -2147483648 / 1000 = 2147483
uint/int = -2147483648 / 1000 = 2147483
uint/uint = -2147483648 / 1000 = 2147483
int num1 = 0x80000000, temp1 = 10000;
unsigned int num2 = 0x80000000, temp2 = 10000;

short num = num1/temp1;
printf("int to short = %d\r\n", num);
num = num2/temp2;
printf("uint to short = %d\r\n", num);

printf("int/int = %d / %d = %d\r\n", num1,temp1, num1/temp1);
printf("int/uint = %d / %d = %d\r\n", num1,temp2, num1/temp2);
printf("uint/int = %d / %d = %d\r\n", num2,temp1, num2/temp1);
printf("uint/uint = %d / %d = %d\r\n", num2,temp2, num2/temp2);
int to short = -18140
uint to short = 18140
int/int = -2147483648 / 10000 = -214748
int/uint = -2147483648 / 10000 = 214748
uint/int = -2147483648 / 10000 = 214748
uint/uint = -2147483648 / 10000 = 214748

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章