Advertisement
Guest User

C exercise for carries calculation

a guest
Oct 10th, 2015
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(int argc, const char * argv[]) {
  4.     int num;
  5.     int idx = 0;
  6.     int carries = 0;
  7.     int bits[11];       // [0]:最右邊bit, [1]:右邊第二個bit, ...
  8.  
  9.     printf("Input a number -> ");
  10.     scanf("%d", &num);
  11.  
  12.     int carry_stop = 0; // 0 means false
  13.     do {
  14.         int bit = num % 2; // 第一次是最右邊bit, 第二次是右邊第二個bit, ...
  15.  
  16.         if (!carry_stop)   // 進位尚未停止的話,bit加1
  17.             bit++;
  18.         bits[idx++] = bit % 2; // 加1以後,記錄目前的第idx個bit (最右邊是第0個,右邊第二個是第1個,...)
  19.  
  20.         if (!carry_stop) {
  21.             if (bit > 1)    // 如果進位尚未停止的話,而且被加到2去的話
  22.                 carries++;  // 進位數+1,之後繼續進位
  23.             else
  24.                 carry_stop = 1; // 否則進位終止
  25.         }
  26.         num >>= 1;      // num往右shift一個bit
  27.     } while (num > 0);
  28.  
  29.     if (!carry_stop)    // 別忘最後進位還沒停止的話,要在最左邊再生一個1出來
  30.         bits[idx++] = 1;
  31.  
  32.     while (--idx >= 0) {
  33.         printf("%d", bits[idx]);
  34.     }
  35.     printf(" %d", carries);
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement