C puzzles詳解【6-8題】

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   strong   for   

第六題

  #include<stdio.h>  int main()  {          int a=10;          switch(a)          {                  case ‘1‘:                      printf("ONE\n");                      break;                  case ‘2‘:                      printf("TWO\n");                      break;                  defa1ut:                      printf("NONE\n");          }          return 0;  }

題目講解:

“defalut”拼字錯誤。

注意a為int型,case後的’1’,’2’為char型。

 

第七題

The following C program segfaults of IA-64, but works fine on IA-32.int main()  {      int* p;      p = (int*)malloc(sizeof(int));      *p = 10;      return 0;  }

知識點講解:

IA-64和IA-32屬於完全不同的處理器架構,兩者的指令集不相互相容。

http://wangcong.org/blog/archives/291的解釋為“IA-64是RISC,不能訪問未對齊的地址”,不太明白。

 

第八題

Here is a small piece of program(again just 14 lines of program) which counts the number of bits set in a number.Input     Output 0     0(0000000) 5     2(0000101) 7     3(0000111)   int CountBits (unsigned int x )  {      static unsigned int mask[] = { 0x55555555,          0x33333333,          0x0F0F0F0F,          0x00FF00FF,          0x0000FFFF          } ;          int i ;          int shift ; /* Number of positions to shift to right*/          for ( i =0, shift =1; i < 5; i ++, shift *= 2)                  x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);          return x;  }Find out the logic used in the above program.

題目講解:

計算一個int型參數二進位模式中1的個數。傳統的演算法要經過32次迴圈,

此演算法最多隻需5次。

以x = 1234為例,

1234的二進位表示為:

0000 0100 1101 0010

第一步:相鄰2位相加

0000 0100 1101 0010 ---> 0000 0100 1001 0001

第二步:相鄰4位相加

0000 0100 1001 0001 ---> 0000 0001 0011 0001

第三步:相鄰8位相加

0000 0001 0011 0001 ---> 0000 0001 0000 0100

第四步:相鄰16位相加

0000 0001 0000 0100 ---> 0000 0000 0000 0101

第五步:相鄰32位相加

無需繼續計算。

結果為5。

至於這麼做為什麼恰巧得到的是1的個數,不解。

 

 

C puzzles詳解【6-8題】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.