支持負數的高精度小數加減法 C++代碼
时间: 2023-07-11 18:30:40 浏览: 147
以下支持负数的高精度小数加减法C++代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string a, string b) {
string ans = "";
int carry = 0;
while (a.length() < b.length()) {
a = "0" + a;
}
while (a.length() > b.length()) {
b = "0" + b;
}
for (int i = a.length() - 1; i >= 0; i--) {
int sum = (a[i] - '0') + (b[i] - '0') + carry;
ans = char(sum % 10 + '0') + ans;
carry = sum / 10;
}
if (carry != 0) {
ans = char(carry + '0') + ans;
}
while (ans[0] == '0' && ans.length() > 1) {
ans.erase(0, 1);
}
return ans;
}
string subtract(string a, string b) {
if (a == b) {
return "0";
}
string ans = "";
bool negative = false;
if (a.length() < b.length() || (a.length() == b.length() && a < b)) {
swap(a, b);
negative = true;
}
while (a.length() < b.length()) {
a = "0" + a;
}
while (a.length() > b.length()) {
b = "0" + b;
}
for (int i = a.length() - 1; i >= 0; i--) {
int diff = (a[i] - '0') - (b[i] - '0');
if (diff < 0) {
diff += 10;
a[i - 1]--;
}
ans = char(diff + '0') + ans;
}
while (ans[0] == '0' && ans.length() > 1) {
ans.erase(0, 1);
}
if (negative) {
ans = "-" + ans;
}
return ans;
}
int main() {
string a, b;
cin >> a >> b;
string sum = add(a, b);
cout << "The sum of " << a << " and " << b << " is " << sum << endl;
string difference = subtract(a, b);
cout << "The difference between " << a << " and " << b << " is " << difference << endl;
return 0;
}
```
该代码使用字符串表示高精度小数,其中负数表示为在最前面添加负号。add函数实现了两个高精度小数的加法,subtract函数实现了两个高精度小数的减法。在subtract函数中,如果a小于b,则先交换a和b,然后在答案前添加负号以表示结果为负数。
阅读全文