用c语言实现高精度加减法
时间: 2023-12-09 19:35:42 浏览: 79
以下是用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 len_a = strlen(a);
int len_b = strlen(b);
int carry = 0;
int i = 0;
while (i < len_a || i < len_b || carry != 0) {
int x = i < len_a ? a[i] - '0' : 0;
int y = i < len_b ? b[i] - '0' : 0;
int sum = x + y + carry;
result[i] = sum % 10 + '0';
carry = sum / 10;
i++;
}
result[i] = '\0';
reverse(result);
}
void subtract(char *a, char *b, char *result) {
int len_a = strlen(a);
int len_b = strlen(b);
int borrow = 0;
int i = 0;
while (i < len_a || i < len_b) {
int x = i < len_a ? a[i] - '0' : 0;
int y = i < len_b ? b[i] - '0' : 0;
int diff = x - y - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[i] = diff + '0';
i++;
}
while (i > 1 && result[i - 1] == '0') {
i--;
}
result[i] = '\0';
reverse(result);
}
int main() {
int n;
scanf("%d", &n);
while (n--) {
char a[MAX_LEN], b[MAX_LEN], result[MAX_LEN];
scanf("%s%s", a, b);
add(a, b, result);
printf("%s + %s = %s\n", a, b, result);
subtract(a, b, result);
printf("%s - %s = %s\n", a, b, result);
}
return 0;
}
```
阅读全文