大整数减法 C语言
发布网友
发布时间:2022-05-30 19:00
我来回答
共1个回答
热心网友
时间:2023-11-01 10:40
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char a[1000],b[1000];
int c[1001];
int x,y,i,j,k;
int blen=0;
int alen=0;
char flag = '+';//用于减法标记负数
int Subtract(char *a, char *b, int len) { //为了避免代码重复,将共同的计算抽出写成函数
int i;
for (i=len-1; i>=0; i--) {
if (a[i] < b[i]) {
c[i] = a[i] + 10 - b[i];
b[i-1]++;
} else {
c[i] = a[i] - b[i];
}
}
return 0;
}
int Subtraction(){
for (i=0;i<100;i++)
{
scanf("%c",&b[i]);
if(b[i]=='\n')
break;
blen++;
}
printf("=");
if(alen>blen)
{
x=(alen-blen);
for(i=blen-1;i>=0;i--)
{
alen--;
b[alen]=b[i];
}
for (i=0;i<x;i++)
b[i]='0';
alen=blen+x;
blen=alen;
} else if (blen > alen) {
x=(blen-alen);
for(i=alen-1;i>=0;i--)
{
blen--;
a[blen]=a[i];
}
for (i=0;i<x;i++)
a[i]='0';
blen=alen+x;
alen=blen;
}
for (i=alen-1;i>=0;i--) {
a[i]=a[i]-'0';
b[i]=b[i]-'0';
}
if (strcmp(a, b) > 0) {
Subtract(a, b, alen);
}else {
flag = '-';
Subtract(b, a, alen);
}
return 0;
}
int Addition(){
for (i=0;i<100;i++)
{ scanf("%c",&b[i]);
if(b[i]=='\n')
break;
blen++;
}
printf("=");
if(alen>blen)
{
x=(alen-blen);
for(i=blen-1;i>=0;i--)
{
alen--;
b[alen]=b[i];
}
for (i=0;i<x;i++)
b[i]='0';
alen=blen+x;
} else if (blen > alen) {
x=(blen-alen);
for(i=alen-1;i>=0;i--)
{
blen--;
a[blen]=a[i];
}
for (i=0;i<x;i++)
a[i]='0';
blen=alen+x;
alen=blen;
}
for (i=alen-1;i>=0;i--) {
a[i]=a[i]-'0';
b[i]=b[i]-'0';
if(c[i+1]+a[i]+b[i]>=10)
{
c[i]=(c[i+1]+a[i]+b[i])/10;
c[i+1] = (c[i+1]+a[i]+b[i])%10;
}
else
{
c[i+1]+=(a[i]+b[i]);
}
}
return 0;
}
int main()
{
for (i=0;i<100;i++)
a[i]=0;
for (i=0;i<100;i++)
b[i]=0;
for (i=0;i<101;i++)
c[i]=0;
for (i=0;i<100;i++)
{
scanf("%c",&a[i]);
if(a[i]=='+')
{
Addition();
goto output1;
}
if(a[i]=='-')
{
Subtraction();
goto output2;
}
alen++;
}
output1:
{
for (i=0;i<=alen;i++)
printf("%d",c[i]);
return 0;
}
output2:
{
printf("%c", flag);
for (i=0;i<alen;i++)
printf("%d",c[i]);
return 0;
}
}
代码运行结果:
123456789-12345
=+123444444
Terminated with return code 0
Press any key to continue ...
123456+111111
=0234567
Terminated with return code 0
Press any key to continue ...
1000000-1
=+0999999
Terminated with return code 0
Press any key to continue ...
1-1000000
=-0999999
Terminated with return code 0
Press any key to continue ...
//对你的代码作了! 希望有助于你的学习。