只用string類實現支持負數的高精度運算(包括高精度乘高精度)
时间: 2023-08-11 18:21:04 浏览: 46
可以使用string类来实现高精度运算,包括高精度乘法和支持负数的高精度运算。下面是一个基本的实现示例:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string s1, string s2) {
string res = "";
int carry = 0, i = s1.size() - 1, j = s2.size() - 1;
while (i >= 0 || j >= 0 || carry != 0) {
int x = i >= 0 ? s1[i--] - '0' : 0;
int y = j >= 0 ? s2[j--] - '0' : 0;
int sum = x + y + carry;
res += sum % 10 + '0';
carry = sum / 10;
}
reverse(res.begin(), res.end());
return res;
}
string sub(string s1, string s2) {
string res = "";
int borrow = 0, i = s1.size() - 1, j = s2.size() - 1;
while (i >= 0 || j >= 0) {
int x = i >= 0 ? s1[i--] - '0' : 0;
int y = j >= 0 ? s2[j--] - '0' : 0;
int diff = x - y - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
res += diff + '0';
}
reverse(res.begin(), res.end());
while (res.size() > 1 && res[0] == '0') res.erase(res.begin());
return res;
}
string mul(string s1, string s2) {
string res(s1.size() + s2.size(), '0');
for (int i = s1.size() - 1; i >= 0; i--) {
int carry = 0;
for (int j = s2.size() - 1; j >= 0; j--) {
int sum = (res[i + j + 1] - '0') + (s1[i] - '0') * (s2[j] - '0') + carry;
res[i + j + 1] = sum % 10 + '0';
carry = sum / 10;
}
res[i] += carry;
}
while (res.size() > 1 && res[0] == '0') res.erase(res.begin());
return res;
}
int main() {
string s1 = "-123456789";
string s2 = "987654321";
string res_add = add(s1, s2);
string res_sub = sub(s1, s2);
string res_mul = mul(s1, s2);
cout << "s1 + s2 = " << res_add << endl;
cout << "s1 - s2 = " << res_sub << endl;
cout << "s1 * s2 = " << res_mul << endl;
return 0;
}
```
在这个实现中,我们定义了三个函数:add、sub和mul。其中add和sub函数分别实现了高精度的加法和减法,mul函数实现了高精度乘法。在实现加法和减法时,我们可以通过比较两个字符串的长度来判断哪个数是负数,并对其进行特殊处理。在实现乘法时,我们使用了竖式乘法的思想,先一位一位地相乘,然后再将结果相加。
需要注意的是,在实现减法和乘法时,我们需要保证被减数和减数、被乘数和乘数的顺序,以便得到正确的结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)