酷代码 AI
菜单
服务商

揭秘!十进制数到负进制数的转换程序及代码详解

```cpp #include <iostream> #include <string> #include <algorithm> using namespace std; // 将十进制数 n 转换为 base 进制(base 为负数) string toNegativeBase(int n, int base) { if (n == 0) return "0"; string result; while (n != 0) { int remainder = n % base; n /= base; // 处理负基数下的余数为负数的情况 if (remainder < 0) { remainder -= base; // 调整余数为正数 n += 1; // 调整商 } // 将余数转换为字符 if (remainder < 10) { result += (char)('0' + remainder); } else { result += (char)('A' + remainder - 10); } } reverse(result.begin(), result.end()); return result; } int main() { int n, base; while (cin >> n >> base) { cout << n << "=" << toNegativeBase(n, base) << "(base" << base << ")" << endl; } return 0; } ``` 代码说明: 1. 核心算法:使用短除法进行进制转换,但需要特殊处理负基数的情况 2. 关键处理: - 当余数为负数时,需要调整余数为正数(`remainder -= base`) - 同时调整商(`n += 1`)以保证计算正确 3. 字符转换: - 余数 0-9 转换为 '0'-'9' - 余数 10+ 转换为 'A'-'Z' 4. 输出格式:严格按照题目要求的 `数值=转换结果(base基数)` 格式 示例运行: ``` 输入:30000 -2 输出:30000=11011010101110000(base-2) 输入:-20000 -2 输出:-20000=1111011000100000(base-2) 输入:28800 -16 输出:28800=19180(base-16) 输入:-25000 -16 输出:-25000=7FB8(base-16) ``` ######[AI问答 | 490点数解答 | 2026-01-20 17:31:14]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]