同时实现高精度加法和减法
时间: 2024-03-14 20:45:53 浏览: 83
好的,下面是同时实现高精度加法和减法的C++代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 高精度加法
string add(string num1, string num2) {
// 先将两个数的位数补齐
int len1 = num1.length(), len2 = num2.length();
if (len1 < len2) {
num1 = string(len2 - len1, '0') + num1;
len1 = len2;
} else {
num2 = string(len1 - len2, '0') + num2;
len2 = len1;
}
// 从低位到高位逐位相加
string result = "";
int carry = 0;
for (int i = len1 - 1; i >= 0; i--) {
int sum = num1[i] - '0' + num2[i] - '0' + carry;
carry = sum / 10;
result += to_string(sum % 10);
}
// 如果还有进位,需要在高位加上进位的1
if (carry == 1) {
result += "1";
}
// 将结果翻转过来
reverse(result.begin(), result.end());
// 去掉前导0
int pos = 0;
while (pos < result.length() && result[pos] == '0') {
pos++;
}
result = result.substr(pos);
if (result.empty()) {
result = "0";
}
return result;
}
// 高精度减法
string subtract(string num1, string num2) {
// 先将两个数的位数补齐
int len1 = num1.length(), len2 = num2.length();
if (len1 < len2) {
num1 = string(len2 - len1, '0') + num1;
len1 = len2;
} else {
num2 = string(len1 - len2, '0') + num2;
len2 = len1;
}
// 从低位到高位逐位相减
string result = "";
int borrow = 0;
for (int i = len1 - 1; i >= 0; i--) {
int diff = num1[i] - num2[i] - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result += to_string(diff);
}
// 去掉前导0
reverse(result.begin(), result.end());
int pos = 0;
while (pos < len1 && result[pos] == '0') {
pos++;
}
result = result.substr(pos);
if (result.empty()) {
result = "0";
}
// 判断结果是否为负数
if (borrow == 1) {
result = "-" + result;
}
return result;
}
int main() {
string num1, num2, op;
cin >> num1 >> op >> num2;
// 根据运算符进行相应的运算
if (op == "+") {
cout << add(num1, num2) << endl;
} else if (op == "-") {
cout << subtract(num1, num2) << endl;
} else {
cout << "Invalid operator!" << endl;
}
return 0;
}
```
这里同时实现了高精度加法函数 `add` 和高精度减法函数 `subtract`。在输入部分和之前一样,使用了 `cin` 来读取输入的两个数字和运算符。然后根据运算符进行相应的运算,并输出结果。
阅读全文