酷代码 AI
菜单
服务商

我的编译器不支持add请修改代码

```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) { b = b.substr(1); 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; } if (aNeg &&!bNeg) { a = a.substr(1); 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; } if (aNeg && bNeg) { a = a.substr(1); b = b.substr(1); swap(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; } int main() { string num1, num2; cin >> num1 >> num2; string result = subtract(num1, num2); cout << result << endl; return 0; } ``` 代码说明: 1. `isGreater` 函数:用于比较两个非负字符串表示的数字大小。 2. `subtract` 函数: - 先判断两个数的正负情况 `aNeg` 和 `bNeg`。 - 当 `a` 为正,`b` 为负时,将 `b` 的负号去掉,然后进行加法运算。 - 当 `a` 为负,`b` 为正时,将 `a` 的负号去掉,进行加法运算后再添加上负号。 - 当 `a` 和 `b` 都为负时,去掉负号并交换两数。 - 对于两数都为正的情况,进行正常减法运算。 3. `main` 函数:读取输入的两个数,调用 `subtract` 函数进行减法运算并输出结果。 [2025-09-15 20:32:29 | AI问答 | 1061点数解答]

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