超级大的整数加减法,输入时要有正负号。希望能写一下代码。c语言
发布网友
发布时间:2022-05-30 19:00
我来回答
共1个回答
热心网友
时间:2023-11-01 10:40
#include <stdio.h>
#include <string.h>
#include <malloc.h>
const int MAXSIZE = 122;
// 完成以字符串形式的两个大数相加。返回字符串形式的和。
// tatol ← addnum1 + addnum2
char *LargeNumberAdd(char const *addnum1,char const *addnum2, char *total) {
int i,j,k = 0,len,result,carry = 0;
int len1 = strlen(addnum1);
int len2 = strlen(addnum2);
for(i = len1 - 1,j = len2 - 1; i >= 0 && j >= 0; --i,--j) {
result = addnum1[i] - '0' + addnum2[j] - '0' + carry;
carry = result/10;
total[k++] = result%10 + '0';
}
while(i >= 0) {
result = addnum1[i--] - '0' + carry;
carry = result/10;
total[k++] = result%10 + '0';
}
while(j >= 0) {
result = addnum2[j--] - '0' + carry;
carry = result/10;
total[k++] = result%10 + '0';
}
if(carry) total[k++] = carry + '0';
total[k] = '\0';
len = strlen(total);
for(i = 0; i < len/2; ++i) {
k = total[i];
total[i] = total[len - 1 - i];
total[len - 1 - i] = k;
}
return total;
}
// 完成以字符串形式的两个大数相减。返回字符串形式的差。
// difference ← subnum1 - subnum2
char *LargeNumberSub(char *subnum1,char *subnum2, char *difference) {
int i,j,k,result,borrow = 0;
int sign = 0,swap = 0;
int maxl,minl;
char *pta,*ptb;
int len1 = strlen(subnum1);
int len2 = strlen(subnum2);
if(len1 == len2) {//两数位数相等时
for(i = 0; i < len1; ++i) {//从高位开始比较,某位大时,这个数就大,相等时继续比较,某位小时,这个数就小
if(subnum1[i] == subnum2[i]) continue;
else if(subnum1[i] < subnum2[i]) {
swap = 1;
break;
}
else {
swap = 0;
break;
}
}
}
if(len2 > len1 || swap) {//减数大于被减数
pta = (char *)malloc((len2 + 1)*sizeof(char)); // pta总是指向绝对值更大的数
ptb = (char *)malloc((len1 + 1)*sizeof(char)); // 而ptb指向绝对值更小的数
strcpy(pta,subnum2);
strcpy(ptb,subnum1);
maxl = len2;
minl = len1;
sign = 1;
}
else {//被减数大于减数
pta = (char *)malloc((len1 + 1)*sizeof(char)); // pta总是指向绝对值更大的数
ptb = (char *)malloc((len2 + 1)*sizeof(char)); // 而ptb指向绝对值更小的数
strcpy(pta,subnum1);
strcpy(ptb,subnum2);
maxl = len1;
minl = len2;
sign = 0;
}
for(i = maxl - 1,j = minl - 1,k = 0; j >= 0; --i,--j) {//从个位开始减
result = pta[i] - ptb[j] - borrow;
if(result < 0) {
result += 10;
borrow = 1;
}
else borrow = 0;
difference[k++] = result + '0';
}
while(i >= 0) {
result = pta[i--] - '0' - borrow;
if(result < 0) {
result += 10;
borrow = 1;
}
else borrow = 0;
difference[k++] = result + '0';
}
--k;
while(difference[k] == '0' && k > 0) --k;//去除差数前端冗余的'0'
if(sign) difference[++k] = '-';
difference[++k] = '\0';
for(i = 0; i < k/2; ++i) {
result = difference[i];
difference[i] = difference[k - 1 - i];
difference[k - 1 - i] = result;
}
free(pta);
free(ptb);
return difference;
}
int main() {
char s[MAXSIZE] = "4561239986547";
char t[MAXSIZE] = "4560658897546";
char result[MAXSIZE + 1];
printf("%s + %s = %s\n",s,t,LargeNumberAdd(s,t,result));
printf("%s - %s = %s\n",s,t,LargeNumberSub(s,t,result));
printf("%s - %s = %s\n",t,s,LargeNumberSub(t,s,result));
return 0;
}