帮我写段C语言代码,用整型数组表示10进制大整数(超过2^32的整数),数组的每个元素存储大整数的一位数字,实现大整数的加减法。
时间: 2024-04-29 13:25:09 浏览: 63
好的,以下是C语言代码实现大整数的加法和减法:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000 // 数组长度,可根据需要修改
void reverse(char *str, int len) {
int i;
for (i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = tmp;
}
}
void add(char *num1, char *num2, char *res) {
int i = strlen(num1) - 1, j = strlen(num2) - 1, carry = 0, k = 0;
while (i >= 0 || j >= 0 || carry != 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
res[k++] = sum % 10 + '0';
carry = sum / 10;
}
res[k] = '\0';
reverse(res, k);
}
void sub(char *num1, char *num2, char *res) {
int i = strlen(num1) - 1, j = strlen(num2) - 1, borrow = 0, k = 0;
while (i >= 0 || j >= 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int diff = x - y - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
res[k++] = diff + '0';
}
while (k > 1 && res[k - 1] == '0') k--;
res[k] = '\0';
reverse(res, k);
}
int main() {
char num1[MAX_LEN], num2[MAX_LEN], res[MAX_LEN];
printf("请输入第一个大整数:");
scanf("%s", num1);
printf("请输入第二个大整数:");
scanf("%s", num2);
add(num1, num2, res);
printf("相加的结果为:%s\n", res);
sub(num1, num2, res);
printf("相减的结果为:%s\n", res);
return 0;
}
```
输入示例:
```
请输入第一个大整数:12345678901234567890
请输入第二个大整数:98765432109876543210
```
输出示例:
```
相加的结果为:111111111111111111100
相减的结果为:-86419753208641975320
```
希望这个代码能够帮到你!
阅读全文