超长正整数减法,错在哪里???
哪一步没有考虑到,或者有什么更好的算法???
望高人指点~~~~
/*
【问题描述】
编写程序实现两个超长正整数(每个最长80位数字)的减法运算。
【输入形式】
从键盘读入两个整数,要考虑输入高位可能为0的情况(如00083)。
1. 第一行是超长正整数A;
2. 第二行是超长正整数B;
【输出形式】
输出只有一行,是长整数A减去长整数B的运算结果,从高到低依次输出各位数字。
要求:若结果为0,则只输出一个0;否则输出的结果的最高位不能为0,并且各位数字紧密输出。
【输入样例】
234098
134098703578230056
【输出样例】
-134098703577995958
【样例说明】
进行两个正整数减法运算, 234098 -134098703578230056 = -134098703577995958。
*/
#include <stdio.h>
#include <string.h>
void cancel (char s[]);
void reverse (char s[]);
int main()
{
char a[100]={'\0'},b[100]={'\0'},temp[100]={'\0'};
int len_a,len_b;
int i;
gets(a);
gets(b);
//去掉数组前面的0
cancel (a);
cancel (b);
len_a=strlen(a);
len_b=strlen(b);
//使前一个数大于后一个数,并输出负号
if (len_a<len_b || ((len_a==len_b)&&(a[0]<b[0]))){
strcpy(temp,a);
strcpy(a,b);
strcpy(b,temp);
printf ("-");
len_a=strlen (a);
len_b=strlen(b);
}
//颠倒a[],b[]
reverse (a);
reverse (b);
//减法计算
for (i=0;i<len_a;i++)
if (a[i]>=b[i]){
if (b[i]==0)
a[i]=a[i];
else
a[i]=a[i]-b[i]+'0';
}
else{
a[i]=a[i]+10-b[i]+'0';
a[i+1]=a[i+1]-'1';//▲▲▲这一步好像不太对???▲▲▲
}
reverse (a);
cancel (a);
printf ("%s\n",a);
return 0;
}
//删除数组前面的0
void cancel (char s[]){
int len_s,i,j;
len_s=strlen(s);
for (i=0;i<len_s-1;i++)
if (s[i]=='0'){
for (j=i;j<len_s-1;j++)
s[j]=s[j+1];
s[j]='\0';
len_s--;
i--;
}
else
break;
}
//颠倒字符串
void reverse (char s[]){
int i,j,len_s;
char temp;
len_s=strlen(s);
for (i=0,j=len_s-1;i<j;i++,j--){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
望高人指点~~~~
/*
【问题描述】
编写程序实现两个超长正整数(每个最长80位数字)的减法运算。
【输入形式】
从键盘读入两个整数,要考虑输入高位可能为0的情况(如00083)。
1. 第一行是超长正整数A;
2. 第二行是超长正整数B;
【输出形式】
输出只有一行,是长整数A减去长整数B的运算结果,从高到低依次输出各位数字。
要求:若结果为0,则只输出一个0;否则输出的结果的最高位不能为0,并且各位数字紧密输出。
【输入样例】
234098
134098703578230056
【输出样例】
-134098703577995958
【样例说明】
进行两个正整数减法运算, 234098 -134098703578230056 = -134098703577995958。
*/
#include <stdio.h>
#include <string.h>
void cancel (char s[]);
void reverse (char s[]);
int main()
{
char a[100]={'\0'},b[100]={'\0'},temp[100]={'\0'};
int len_a,len_b;
int i;
gets(a);
gets(b);
//去掉数组前面的0
cancel (a);
cancel (b);
len_a=strlen(a);
len_b=strlen(b);
//使前一个数大于后一个数,并输出负号
if (len_a<len_b || ((len_a==len_b)&&(a[0]<b[0]))){
strcpy(temp,a);
strcpy(a,b);
strcpy(b,temp);
printf ("-");
len_a=strlen (a);
len_b=strlen(b);
}
//颠倒a[],b[]
reverse (a);
reverse (b);
//减法计算
for (i=0;i<len_a;i++)
if (a[i]>=b[i]){
if (b[i]==0)
a[i]=a[i];
else
a[i]=a[i]-b[i]+'0';
}
else{
a[i]=a[i]+10-b[i]+'0';
a[i+1]=a[i+1]-'1';//▲▲▲这一步好像不太对???▲▲▲
}
reverse (a);
cancel (a);
printf ("%s\n",a);
return 0;
}
//删除数组前面的0
void cancel (char s[]){
int len_s,i,j;
len_s=strlen(s);
for (i=0;i<len_s-1;i++)
if (s[i]=='0'){
for (j=i;j<len_s-1;j++)
s[j]=s[j+1];
s[j]='\0';
len_s--;
i--;
}
else
break;
}
//颠倒字符串
void reverse (char s[]){
int i,j,len_s;
char temp;
len_s=strlen(s);
for (i=0,j=len_s-1;i<j;i++,j--){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
...全文


