酷代码 AI
菜单
服务商

C++实现:十进制数到负进制数的奇妙转换(附代码详解)

```cpp #include <iostream> #include <string> #include <algorithm> using namespace std; // 将十进制数转换为负进制数 string convertToNegativeBase(int num, int base) { if (num == 0) return "0"; string result = ""; while (num != 0) { int remainder = num % base; num /= base; if (remainder < 0) { // 处理余数为负的情况 remainder -= base; num++; } if (remainder < 10) { result += to_string(remainder); } else { // 处理大于9的数码 result += static_cast<char>('A' + remainder - 10); } } reverse(result.begin(), result.end()); return result; } int main() { int n, R; cin >> n >> R; string negativeBaseNumber = convertToNegativeBase(n, R); cout << n << "=" << negativeBaseNumber << "(base" << R << ")" << endl; return 0; } ``` 代码说明: 1. 函数 `convertToNegativeBase`: - 该函数用于将十进制数 `num` 转换为负进制数,以字符串形式返回。 - 若 `num` 为 0,直接返回 "0"。 - 使用循环,每次计算当前 `num` 对目标负进制 `base` 的余数,然后更新 `num` 为商。 - 若余数为负数,则通过 `remainder -= base` 和 `num++` 调整余数和商,确保余数为非负。 - 若余数小于 10,直接将其转换为字符串添加到结果中;若大于等于 10,则转换为对应的字母(如 A 表示 10,B 表示 11 等)。 - 最后将结果字符串反转。 2. 主函数 `main`: - 从标准输入读取十进制数 `n` 和负进制基数 `R`。 - 调用 `convertToNegativeBase` 函数将 `n` 转换为负进制数。 - 按照指定格式输出结果。 ######[AI问答 | 526点数解答 | 2026-02-07 20:37:30]

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