用整型数组表示10进制大整数(超过2^32的整数),数组的每个元素存储大整数的一位数字,实现大整数的加减法。c++
时间: 2024-03-18 13:39:02 浏览: 15
下面是使用 C++ 实现用整型数组表示10进制大整数的加减法的示例代码。假设数组 `a` 和 `b` 分别存储两个大整数,数组 `c` 存储计算结果,数组 `len` 存储大整数的位数。
```c++
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int MAX_LEN = 1000;
void add(int a[], int b[], int c[], int len[]) {
int carry = 0;
int i;
for (i = 0; i < len[0] || i < len[1]; i++) {
int sum = a[i] + b[i] + carry;
c[i] = sum % 10;
carry = sum / 10;
}
if (carry > 0) {
c[i] = carry;
len[2] = i + 1;
} else {
len[2] = i;
}
}
void sub(int a[], int b[], int c[], int len[]) {
int borrow = 0;
int i;
for (i = 0; i < len[0] || i < len[1]; i++) {
int diff = a[i] - b[i] - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
c[i] = diff;
}
while (i > 0 && c[i - 1] == 0) {
i--;
}
len[2] = i;
}
int main() {
int a[MAX_LEN], b[MAX_LEN], c[MAX_LEN];
int len[3] = {0};
string str_a, str_b;
cout << "请输入两个大整数,以空格分隔:" << endl;
cin >> str_a >> str_b;
len[0] = str_a.length();
len[1] = str_b.length();
int i;
for (i = 0; i < len[0]; i++) {
a[i] = str_a[len[0] - i - 1] - '0';
}
for (i = 0; i < len[1]; i++) {
b[i] = str_b[len[1] - i - 1] - '0';
}
add(a, b, c, len);
cout << "相加的结果为:" << endl;
for (i = len[2] - 1; i >= 0; i--) {
cout << c[i];
}
cout << endl;
sub(a, b, c, len);
cout << "相减的结果为:" << endl;
for (i = len[2] - 1; i >= 0; i--) {
cout << c[i];
}
cout << endl;
return 0;
}
```
在这个示例代码中,我们使用了 C++ 的 string 类型来读取输入的大整数,避免了输入超过数组长度的问题。其他的实现方式和 C 语言的示例代码类似。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)