你的代码只有加法,没有减法
时间: 2024-01-13 09:02:16 浏览: 33
对不起,我的回答有误。以下是实现两个大整数的减法并输出结果的代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void add(char a[], char b[], char result[]);
void reverse(char s[]);
void subtract(char a[], char b[], char result[]) {
int len_a = strlen(a), len_b = strlen(b), borrow = 0;
int i = 0, j = 0, k = 0;
char temp_a[MAX_LEN], temp_b[MAX_LEN];
// 将被减数和减数的每一位取10之后再交换,即减去b变成加上-b,转化为加法
for (int i = 0; i < len_a; i++) {
temp_a[i] = a[len_a - 1 - i];
}
for (int i = 0; i < len_b; i++) {
temp_b[i] = '9' - (b[len_b - 1 - i] - '0') + '0';
}
while (i < len_a || j < len_b) {
int x = i < len_a ? temp_a[i] - '0' : 0;
int y = j < len_b ? temp_b[j] - '0' : 0;
int diff = x + y + borrow;
result[k++] = diff % 10 + '0';
borrow = diff / 10 ? 0 : 1;
i++;
j++;
}
while (k > 1 && result[k - 1] == '0') {
k--;
}
result[k] = '\0';
reverse(result);
}
int main() {
char a[MAX_LEN], b[MAX_LEN], result[MAX_LEN];
printf("请输入两个大整数:\n");
scanf("%s%s", a, b);
subtract(a, b, result);
printf("结果为:%s\n", result);
return 0;
}
void add(char a[], char b[], char result[]) {
int len_a = strlen(a), len_b = strlen(b), carry = 0;
int i = 0, j = 0, k = 0;
while (i < len_a || j < len_b) {
int x = i < len_a ? a[i] - '0' : 0;
int y = j < len_b ? b[j] - '0' : 0;
int sum = x + y + carry;
result[k++] = sum % 10 + '0';
carry = sum / 10;
i++;
j++;
}
if (carry > 0) {
result[k++] = carry + '0';
}
result[k] = '\0';
}
void reverse(char s[]) {
int len = strlen(s), i = 0, j = len - 1;
while (i < j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
```
算法步骤:
1. 定义一个数组a[]用于存储大整数;
2. 输入两个大整数a和b,将b的每一位取10之后再交换,即减去b变成加上-b,转化为加法;
3. 利用a[i]+b[i]+borrow(borrow代表借位)的值计算第i位的差d[i]和新借位,根据d[i]%10存储a[i+1]的值,同时根据(d[i]>=0)判断是否产生新借位;
4. 当a和-b的所有位数都求差完之后,去除结果的前导零;
5. 输出结果;
6. 对于加法,可以直接调用之前的add函数实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)