大整数减法c语言代码
时间: 2024-06-15 11:07:56 浏览: 70
C语言--大整数减法
当处理大整数减法时,我们需要考虑两个大整数的长度以及借位的情况。以下是一个简单的C语言代码示例,用于实现大整数减法:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
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 subtract(char* num1, char* num2, char* result) {
int len1 = strlen(num1);
int len2 = strlen(num2);
// 反转两个大整数
reverse(num1);
reverse(num2);
int borrow = 0;
int i;
for (i = 0; i < len2; i++) {
int diff = (num1[i] - '0') - (num2[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[i] = diff + '0';
}
// 处理较长的大整数剩余的位数
for (; i < len1; i++) {
int diff = (num1[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[i] = diff + '0';
}
// 去除结果前面的0
while (result[i - 1] == '0' && i > 1) {
i--;
}
result[i] = '\0';
// 反转结果
reverse(result);
}
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;
}
```
请注意,此代码仅适用于非负整数的减法运算。如果需要处理负数或更复杂的情况,请根据具体需求进行修改。
阅读全文