用C++写实现大整数减法
时间: 2024-06-03 20:07:33 浏览: 7
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000 // 大整数最大长度
void reverse(char *s) { // 反转字符串
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char tmp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = tmp;
}
}
int main() {
char a[MAX_LEN], b[MAX_LEN], c[MAX_LEN];
scanf("%s %s", a, b);
int len_a = strlen(a), len_b = strlen(b);
if (len_a < len_b || (len_a == len_b && strcmp(a, b) < 0)) { // 保证 a >= b
char tmp[MAX_LEN];
strcpy(tmp, a);
strcpy(a, b);
strcpy(b, tmp);
int tmp_len = len_a;
len_a = len_b;
len_b = tmp_len;
}
reverse(a); // 反转字符串,方便从低位到高位计算
reverse(b);
int carry = 0, i;
for (i = 0; i < len_b; i++) { // 从低位到高位依次计算
int tmp = a[i] - '0' - (b[i] - '0') - carry;
carry = 0;
if (tmp < 0) { // 如果需要借位
carry = 1;
tmp += 10;
}
c[i] = tmp + '0'; // 将计算结果转换为字符
}
for (; i < len_a; i++) {
int tmp = a[i] - '0' - carry;
carry = 0;
if (tmp < 0) {
carry = 1;
tmp += 10;
}
c[i] = tmp + '0';
}
while (i > 0 && c[i - 1] == '0') i--; // 去掉高位的0
if (i == 0) printf("0"); // 如果结果为0,直接输出0
else {
c[i] = '\0';
reverse(c);
printf("%s", c);
}
return 0;
}
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)