-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.
你只出了1位。非常接近。你做了什麼來嘗試和調試呢? – kaylum