c - 如何从输入中获取数字并将其打印出来?
问题描述
我正在尝试制作一个将八进制数转换为常规整数的程序。我的代码看起来像这样。
#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
:的最后一个 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
}
这会产生您的预期结果。
推荐阅读
- android - 与模拟器/ios 相比,cordova 应用程序在物理 android 上的路由何时会有所不同
- sql - 基于多个约束的最大值
- node.js - 将 CSV 流与节点合并,尝试发出标头一次且仅一次
- web-services - 如何在 Windows 上启动本地 Web 服务器?
- django - 使用基本 Django 应用程序访问 sqlite3 时出现权限错误
- amazon-web-services - Kinesis Stream 未获取日志
- ios - 选择器视图隐藏相应的文本字段
- java - 将数组保存在 Vector/ArrayList 中
- javascript - 未捕获的类型错误:global$4 未定义
- postgresql - Django 自动更改日期时间