首页 > 解决方案 > 如何从输入中获取数字并将其打印出来?

问题描述

我正在尝试制作一个将八进制数转换为常规整数的程序。我的代码看起来像这样。

#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

但我不知道如何具体解决问题。

标签: c

解决方案


printf:的最后一个 arg* (num >> (3 * i) & 7)必须是* (num >> (3 * i) & 7)( *, not &)

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
        }

这会产生您的预期结果。


推荐阅读