用C语言编写一个程序,用整型数组表示超过2的32次方的整数,数组的每个元素存储大整数的一位数字,实现大整数的加减法
时间: 2024-02-21 17:02:14 浏览: 62
好的,我可以为您提供一个简单的大整数加法和减法的C程序,如下所示:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
void reverse(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
void add(char *a, char *b, char *result) {
int len1 = strlen(a);
int len2 = strlen(b);
int carry = 0;
int i, j;
for (i = len1 - 1, j = len2 - 1; i >= 0 && j >= 0; i--, j--) {
int sum = (a[i] - '0') + (b[j] - '0') + carry;
carry = sum / 10;
result[i] = (sum % 10) + '0';
}
while (i >= 0) {
int sum = (a[i] - '0') + carry;
carry = sum / 10;
result[i] = (sum % 10) + '0';
i--;
}
while (j >= 0) {
int sum = (b[j] - '0') + carry;
carry = sum / 10;
result[j] = (sum % 10) + '0';
j--;
}
if (carry != 0) {
result[strlen(result)] = carry + '0';
}
}
void subtract(char *a, char *b, char *result) {
int len1 = strlen(a);
int len2 = strlen(b);
int borrow = 0;
int i, j;
for (i = len1 - 1, j = len2 - 1; i >= 0 && j >= 0; i--, j--) {
int diff = (a[i] - '0') - (b[j] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[i] = diff + '0';
}
while (i >= 0) {
int diff = (a[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[i] = diff + '0';
i--;
}
reverse(result);
}
int main() {
char a[MAX_LEN], b[MAX_LEN], result[MAX_LEN];
printf("Enter the first number: ");
scanf("%s", a);
printf("Enter the second number: ");
scanf("%s", b);
printf("The sum of the two numbers is: ");
add(a, b, result);
printf("%s\n", result);
printf("The difference between the two numbers is: ");
subtract(a, b, result);
printf("%s\n", result);
return 0;
}
```
这个程序中,我们使用了 `reverse()` 函数来反转一个字符串, `add()` 函数来实现两个大整数的加法, `subtract()` 函数来实现两个大整数的减法。您可以在主函数中输入两个大整数,并计算它们的和与差。
阅读全文