請用string 實現高精度減法
时间: 2023-07-21 12:23:48 浏览: 41
好的,以下是使用 string 实现高精度减法的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
string subtract(string num1, string num2) {
// 确保 num1 >= num2
if (num1.length() < num2.length() || (num1.length() == num2.length() && num1 < num2)) {
swap(num1, num2);
}
string result = "";
int carry = 0;
int diff;
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0; i--, j--) {
int digit1 = num1[i] - '0';
int digit2 = j >= 0 ? num2[j] - '0' : 0;
diff = digit1 - digit2 - carry;
carry = 0;
if (diff < 0) {
diff += 10;
carry = 1;
}
result = to_string(diff) + result;
}
// 去掉前导零
while (result.length() > 1 && result[0] == '0') {
result.erase(0, 1);
}
return result;
}
int main() {
string num1 = "987654321";
string num2 = "123456789";
string result = subtract(num1, num2);
cout << num1 << " - " << num2 << " = " << result << endl;
return 0;
}
```
在这个示例中,我们定义了一个 `subtract()` 函数,它接受两个字符串参数 `num1` 和 `num2`,并返回它们的差。首先,我们将 `num1` 和 `num2` 中的数字逆序遍历(从个位到最高位),并从右向左逐位相减。如果当前位的 `num1` 数字小于 `num2` 数字,则需要向高位借位。
最后,我们需要去掉结果中的前导零,并将结果作为字符串返回。
在主函数中,我们测试了这个函数,并输出了计算结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.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)