有符號與無符號 整形變數 相加和比較
阿新 • • 發佈:2019-02-06
int main() {
unsigned int a = 1;
int b = -20;
std::cout << ((a + b > 6) ? ">6" : "<6");
return 0;
}
輸出 >6
因為:int 轉為unsigned int
int main() {
unsigned int a = 1;
int b = -1;
std::cout << ((a + b > 1) ? ">1" : "<1");
return 0;
}
輸出 <1
因為: - 1 32位全為1,再加上1。結果為0
輸出 >1int main() { unsigned int a = 1; char b = -20; unsigned int c = (unsigned int)b;//c=4294967276 unsigned char d = (unsigned char)b;//d=236 std::cout << (((c = a + b) > 1) ? ">1" : "<1");//c=4294967277 return 0; }
因為:由註釋得:將char型 - 20 轉成了 unsigned int 進行運算