酷代码 AI
菜单
服务商

输入的数可能是负数,请修改代码

```cpp #include <iostream> #include <string> #include <algorithm> using namespace std; bool isGreater(const string& a, const string& b) { if (a.length() != b.length()) { return a.length() > b.length(); } return a > b; } string subtract(string a, string b) { bool aNeg = a[0] == '-'; bool bNeg = b[0] == '-'; if (aNeg && bNeg) { a = a.substr(1); b = b.substr(1); swap(a, b); } else if (aNeg) { a = a.substr(1); return "-" + add(a, b); } else if (bNeg) { b = b.substr(1); return add(a, b); } if (a == b) { return "0"; } bool negative = false; if (!isGreater(a, b)) { swap(a, b); negative = true; } string result; int carry = 0; int i = a.length() - 1, j = b.length() - 1; while (i >= 0 || j >= 0) { int x = (i >= 0) ? a[i] - '0' : 0; int y = (j >= 0) ? b[j] - '0' : 0; int diff = x - y - carry; if (diff < 0) { diff += 10; carry = 1; } else { carry = 0; } result.push_back(diff + '0'); i--; j--; } while (result.length() > 1 && result.back() == '0') { result.pop_back(); } if (negative) { result.push_back('-'); } reverse(result.begin(), result.end()); return result; } string add(string a, string b) { string result; int carry = 0; int i = a.length() - 1, j = b.length() - 1; while (i >= 0 || j >= 0 || carry) { int x = (i >= 0) ? a[i] - '0' : 0; int y = (j >= 0) ? b[j] - '0' : 0; int sum = x + y + carry; result.push_back(sum % 10 + '0'); carry = sum / 10; i--; j--; } reverse(result.begin(), result.end()); return result; } int main() { string num1, num2; cin >> num1 >> num2; string result = subtract(num1, num2); cout << result << endl; return 0; } ``` 代码说明: 1. `isGreater` 函数:用于比较两个非负字符串表示的数字大小。 2. `subtract` 函数: - 首先判断两个数的正负情况,根据不同情况转换为合适的计算方式。 - 若两数都为负,交换两数并按正数处理。 - 若 `a` 为负,`b` 为正,计算 `-(|a| + b)`。 - 若 `a` 为正,`b` 为负,计算 `a + |b|`。 - 对于两数都为正的情况,进行正常减法运算。 3. `add` 函数:用于高精度数的加法,在减法处理正负情况时会用到。 4. `main` 函数:读取输入的两个数,调用 `subtract` 函数进行减法运算并输出结果。 [2025-09-15 20:31:27 | AI问答 | 926点数解答]

相关提问
请收藏新域名:pdcd.cn
发财导航,免费问AI
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]