高精度乘法c++代码
时间: 2023-09-20 12:14:25 浏览: 156
在 C++ 中实现高精度乘法可以使用字符串或数组来存储大整数,并通过模拟手工乘法的方式进行计算。以下是一个示例代码,展示了如何实现高精度乘法:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
std::string multiply(std::string num1, std::string num2) {
int len1 = num1.length();
int len2 = num2.length();
std::vector<int> result(len1 + len2, 0);
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
int product = (num1[i] - '0') * (num2[j] - '0');
int pos1 = i + j;
int pos2 = i + j + 1;
int sum = product + result[pos2];
result[pos1] += sum / 10;
result[pos2] = sum % 10;
}
}
std::string res = "";
for (int digit : result) {
if (!(res.empty() && digit == 0)) {
res += std::to_string(digit);
}
}
return res.empty() ? "0" : res;
}
int main() {
std::string num1 = "123456789";
std::string num2 = "987654321";
std::string product = multiply(num1, num2);
std::cout << "Product: " << product << std::endl;
return 0;
}
```
在上述代码中,我们定义了一个 `multiply` 函数,它接受两个以字符串形式表示的大整数 `num1` 和 `num2`,并返回它们的乘积。我们使用一个 `result` 数组来存储中间结果,并通过两层循环模拟手工乘法的过程,逐位相乘并累加到正确的位置上。
注意,我们将每一位数字都作为整数存储在 `result` 数组中,并在最后将其转换为字符串表示的结果。
以上是一个简单的高精度乘法示例,您可以根据实际需求进行修改和扩展。希望能对您有所帮助!如果还有其他问题,请随时提问。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.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://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)