今天面試面試官讓讀下面這段代碼,然后說出代碼作用,看了10分鐘后被面試官打斷,真沒看出這代碼到底是做什么的,取得面試官同意后拍照,自己在電腦上跑了跑,沒看出這到底是要干什么.void send(int* to, int* from, int count){ int n = (count+7)/8; switch(count%8) { case 0: do{ *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; } while(--n>0); }}其實真正的結構是這樣的: void send(int* to, int* from, int count) { int n = (count+7)/8; switch(count%8) { case 0: do { *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; } while(--n>0); } }
2 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
貌似是在拷貝數組, (count + 7) / 8
是在計算循環次數,主要是考慮有余數的情況,而且避開 0,因為
(0 + 7) / 8 == 0; (1 + 7) / 8 == 1; ... (8 + 7) / 8 == 1; (9 + 7) / 8 == 2;
所以可以認為是把從 0 起始的數組變成了從 1 起始的數組,而且按 8 個一組分
case 可以當 label 看待,switch 只有第一次循環有效,也就是處理余數部分,比如 count = 12 的時候直接從 4 開始但一輪循環完成下一個循環的時候肯定是從 7 開始的。
看程序大概是這么回事
添加回答
舉報
0/150
提交
取消