1. 程式人生 > >unsigned int表示負數問題

unsigned int表示負數問題

pac tex std sso %d word p s col lai

1 2 3 4 5 6 7 8 9 10 11 12 #include<stdio.h> int main() { unsigned char i=7; int j=0; for(;i>0;i-=3) { ++j; } printf("%d\n",j); return 0; }
請問該程序的輸出是多少? ———————————————— unsigned char 8位數據位,範圍0-255,
所以-2(11111110)時,溢出變成254;
同理-1(11111111)時,溢出變成255;
最後減到0時,不滿足循環條件,for停止。
剛好173次。
7 4 1 ==> 共(7-1)/3+1=3次(1-3=-2,即254,繼續循環)
254 251 ... 5 2 ==> 共(254-2)/3+1=85次(2-3=-1,即255,繼續循環)
255 252 ... 6 3 ==> 共(255-5)/3+1=85次(3-3=0,退出循環)
所以總共173次。

unsigned int表示負數問題