C语言,编写长度在10位到1000位的任意两个长整数的加减运算,输出运算结果
时间: 2023-07-20 22:35:46 浏览: 200
好的,我可以为您提供一种 C 语言代码实现,如下所示:
```c
#include <stdio.h>
#include <string.h>
#define MAXLEN 1005
void reverse(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
void add(char *a, char *b, char *sum) {
int len_a = strlen(a), len_b = strlen(b);
int carry = 0, idx = 0;
for (int i = len_a - 1, j = len_b - 1; i >= 0 || j >= 0; i--, j--) {
int num_a = (i >= 0) ? (a[i] - '0') : 0;
int num_b = (j >= 0) ? (b[j] - '0') : 0;
int digit_sum = num_a + num_b + carry;
sum[idx++] = digit_sum % 10 + '0';
carry = digit_sum / 10;
}
if (carry) {
sum[idx++] = carry + '0';
}
sum[idx] = '\0';
reverse(sum);
}
void subtract(char *a, char *b, char *diff) {
int len_a = strlen(a), len_b = strlen(b);
int borrow = 0, idx = 0;
for (int i = len_a - 1, j = len_b - 1; i >= 0 || j >= 0; i--, j--) {
int num_a = (i >= 0) ? (a[i] - '0') : 0;
int num_b = (j >= 0) ? (b[j] - '0') : 0;
int digit_diff = num_a - num_b - borrow;
if (digit_diff < 0) {
digit_diff += 10;
borrow = 1;
} else {
borrow = 0;
}
diff[idx++] = digit_diff + '0';
}
while (idx > 1 && diff[idx - 1] == '0') {
idx--;
}
diff[idx] = '\0';
reverse(diff);
}
int main() {
char a[MAXLEN], b[MAXLEN], sum[MAXLEN], diff[MAXLEN];
scanf("%s %s", a, b);
// 计算和
add(a, b, sum);
printf("Sum: %s\n", sum);
// 计算差
subtract(a, b, diff);
printf("Difference: %s\n", diff);
return 0;
}
```
这个程序实现了两个长整数的加减运算,并输出运算结果。其中,`add` 函数实现了加法运算,`subtract` 函数实现了减法运算,`reverse` 函数用于翻转字符串。您可以在 `main` 函数中输入两个长整数,然后调用 `add` 和 `subtract` 函数计算它们的和和差,并输出结果。
阅读全文