p2142 高精度减法c语言
时间: 2024-02-15 17:59:59 浏览: 78
以下是C语言实现高精度减法的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
void subtract(char num1[], char num2[], char result[]) {
int len1 = strlen(num1);
int len2 = strlen(num2);
int carry = 0;
int i, j;
// 从个位开始逐位相减
for (i = len1 - 1, j = len2 - 1; i >= 0 || j >= 0; i--, j--) {
int digit1 = (i >= 0) ? num1[i] - '0' : 0;
int digit2 = (j >= 0) ? num2[j] - '0' : 0;
int diff = digit1 - digit2 - carry;
if (diff < 0) {
diff += 10;
carry = 1;
} else {
carry = 0;
}
result[i] = diff + '0';
}
result[len1] = '\0';
}
int main() {
char num1[MAX_LEN];
char num2[MAX_LEN];
char result[MAX_LEN];
printf("请输入被减数:");
scanf("%s", num1);
printf("请输入减数:");
scanf("%s", num2);
subtract(num1, num2, result);
printf("减法结果:%s\n", result);
return 0;
}
```
阅读全文