我们要求C语言编个程序,实现无限位数的四则运算,我用数组编了,但是不通过,大家能看看吗?还是友人能编吗?
我们明天交作业了,谢谢大家!
这是我编的,但是用的是数组,很难实现无限位数的运算.
#include<stdio.h>
#include<stdlib.h>
int a[10000],b[10000],c[10000];
int ha,hb,hc,ta,tb,tc,s=0;
char symbol;
void init();
void out();
void add();
void del();
void mul();
void dev();
int big();
main()
{
init();
switch(symbol)
{
case '+': {add(); break;}
case '-': {del(); break;}
case '*': {mul(); break;}
case '/': {dev(); break;}
}
out();
system("pause");
return 0;
}
void add()
{
int i,j,k;
int na,nb;
if (ta-ha>tb-hb)
{ tc=ta; hc=ha;}
else
{ tc=tb; hc=hb;}
for (i=tc; i>=hc; i--)
{
if (ta-(tc-i)<ha)
na=0;
else na=a[ta-(tc-i)];
if (tb-(tc-i)<hb)
nb=0;
else nb=b[tb-(tc-i)];
c[i]=na+nb;
}
for (i=tc; i>=hc+1; i--)
if (c[i]>=10)
{ c[i-1]++; c[i]%=10;}
if (c[hc]>=10)
{ hc--; c[hc]=1; c[hc+1]%=10;}
}
void del()
{
int i,j,k;
int t,h,w;
int na,nb;
if (!big())
{ printf("-");
if (ha<hb)
h=ha;
else h=hb;
if (ta>tb)
t=ta;
else
t=tb;
for (i=h; i<=t; i++)
{w=a[i]; a[i]=b[i]; b[i]=w;}
t=ta; h=ha; ta=tb; ha=hb; tb=t; hb=h;
}
for (i=ta; i>=ha; i--)
{
na=a[i];
if (tb-(ta-i)<hb)
nb=0;
else nb=b[tb-(ta-i)];
c[i]=na-nb;
}
tc=ta; hc=ha;
for (i=tc; i>=hc+1; i--)
if (c[i]<0)
{ c[i-1]--; c[i]+=10;}
while (hc<tc && c[hc]==0)
hc++;
}
void mul()
{
int i,j,k,na,nb;
hc=1; tc=(ta-ha+1+tb-hb+1);
for (i=hc; i<=tc; i++)
c[i]=0;
for (i=ta; i>=ha; i--)
for (j=tb; j>=hb; j--)
{
c[tc-(ta-i+tb-j)]+=a[i]*b[j];
}
for (i=tc; i>=hc+1; i--)
if (c[i]>=10)
{c[i-1]+=c[i]/10; c[i]%=10;}
if (c[hc]==0)
hc++;
}
void dev()
{
int i,j,k,na,nb;
while (big())
{
del();
s++;
ha=hc; ta=tc;
for(i=hc; i<=tc; i++)
a[i]=c[i];
}
}
int big()
{
int i;
if (ta-ha>tb-hb)
return 1;
else if (ta-ha<tb-hb)
return 0;
else
for (i=ha; i<=ta; i++)
if (a[i]>b[hb+(i-ha)])
return 1;
else if (a[i]<b[hb+(i-ha)])
return 0;
return 1;
}
void init()
{
char ch;
symbol=getchar();
while (symbol != '+' && symbol != '-' && symbol != '*' && symbol != '/')
symbol=getchar();
ha=1; ta=0;
ch=getchar();
while (ch!='#')
{
if (ch>='0' && ch<='9')
{ ta++; a[ta]=ch-'0';}
ch=getchar();
}
hb=1; tb=0;
ch=getchar();
while (ch!='#')
{
if (ch>='0' && ch<='9')
{ tb++; b[tb]=ch-'0';}
ch=getchar();
}
}
void out()
{
int i;
if (symbol=='/')
printf("%d 余",s);
for (i=hc; i<=tc; i++)
printf("%d",c[i]);
printf("\n");
}