问题描述
我正在尝试制作一个将八进制数字转换为规则整数的程序。我的代码看起来像这样。
#include <stdio.h>
int main(void) {
unsigned int c,num = 0,ct = 0;
printf("Please input a positive octal integer and end with pressing Enter:\n");
// Read the octal string,at most 10 characters.
while ((c = getchar()) != '\n' && ((c >= '0' && c <= '9') && ct++ < 11)) {
// Convert the input string to an value storing in int
num = num << 3 | (c - '0');
}
// If the input is not valid,output the error message.
if (c != '\n') {
printf("ERROR: the input should be an octal string containing 0-7,with length less than 11!\n");
} else { // Output the conversion table.
printf("i\t8^i\tdigit\tproduct\n");
for (int i = 0; i < ct; i++) {
printf("%u\t%u\t%u\t%u\n",i,// Position i
1 << (3 * i),// Get 8 ** i
num >> (3 * i) & 7,// Get bit at position i
(1 << (3 * i)) * (num >> (3 & i) & 7)); // Multiply 8 ** i to the bit at position i
}
// Output the decimal value
printf("Decimal value: %d\n",num);
}
return 0;
}
结果应为:
Please input a positive octal integer and end with pressing Enter:
7326
i 8^i digit product
0 1 6 6
1 8 2 16
2 64 3 192
3 512 7 3584
Decimal value: 3798
但是它看起来像这样:
Please input a positive octal integer and end with pressing Enter:
7326
i 8^i digit product
0 1 6 6
1 8 2 24
2 64 3 320
3 512 7 1024
Decimal value: 3798
我相信问题出在第32-33行:
num >> (3 * i) & 7,// Get bit at position i
(1 << (3 * i)) * (num >> (3 & i) & 7)); // Multiply 8 ** i to the bit at position i
但是我不知道如何具体解决问题。
解决方法
printf
:* (num >> (3 * i) & 7)
的最后一个参数必须为* (num >> (3 * i) & 7)
(*
,而不是&
)
printf("%u\t%u\t%u\t%u\n",i,// Position i
1 << (3 * i),// Get 8 ** i
num >> (3 * i) & 7,// Get bit at position i
(1 << (3 * i)) * (num >> (3 * i) & 7)); // Multiply 8 ** i to the bit at position i
}
这会产生预期的结果。