2015-05-03 104 views
-2

遞歸反轉位程序。遞歸位反轉程序

#include <stdio.h> 
#include <conio.h> 

void displayBits(unsigned value); 
void reverseBits(unsigned value, unsigned c); 

int main(void) 
{ 
    unsigned value; 
    unsigned c = 32; 

    printf("Enter a unsigned integer: "); 
    scanf("%u", &value); 

    displayBits(value); 
    printf("%10s", "Reversed: "); 
    reverseBits(value , c); 

    getche(); 
    return 0; 
} 

void displayBits(unsigned value) 
{ 
    unsigned c; 
    unsigned mask = 1 << 31; 

    printf("%10u = ", value); 

    for(c = 1; c <= 32; c++){ 
      putchar(value & mask ? '1' : '0'); 
      value <<= 1; 
      if(c % 8 == 0) 
       putchar(' '); 

      }//end for  
    putchar('\n'); 

} 

void reverseBits(unsigned value, unsigned c) 
{ 
    unsigned mask = 1 << 31; 

    if(c == 0){ 
     return; 

     }//end if 

    else{  
      value <<= 1; 
      reverseBits(value , c - 1); 
      putchar(value & mask ? '1' : '0'); 
      if(c % 8 == 0){ 
       putchar(' '); 

       }//end if 
      }//end else 
} 

當我輸入15它輸出

01111000 00000000 00000000 00000000 

,而不是

11110000 00000000 00000000 000000000. 
+2

你只出了1位。非常接近。你做了什麼來嘗試和調試呢? – kaylum

回答

0
else{  
     value <<= 1;//<-- Value has been changed before it can be used 
     reverseBits(value , c - 1); 
     putchar(value & mask ? '1' : '0'); 
     if(c % 8 == 0){ 
      putchar(' '); 

      }//end if 
     }//end else 

else { 
    reverseBits(value << 1, c - 1); 
    putchar(value & mask ? '1' : '0'); 
    if(c % 8 == 0){ 
     putchar(' '); 
    } 
} 
0

替換如果您會嘗試使用當前代碼來設置所有位的數字,然後您就會知道您的錯誤。如果所有位都置位,程序將返回o/p。

01111111 11111111 11111111 11111111 
instead of 
11111111 11111111 11111111 11111111 

那是因爲你正在改變的給定數量的32倍(位置)第一位,而不是31,所以你必須改變你的邏輯。你可以像@BLUEPIXY指出的那樣去做。