#include"stdio.h"
//定义无符号结构体。最大可储存100位数。
typedef struct shu
{
int x[100];
}shu;
shu plus(shu a,shu b)//加法函数
{
shu c;// C 为最后返回的结果。
for(int i=0;i<100;i++)
{
c.x[i]=0;//一般系统会把各个位置重置为 0 。但保险起见我们再手动设置一下。
}
int a1=99,b1=99;// a1,b1,为输入两个数的最大位数。
while(a.x[a1]==0&&a1>0)//从99位起,只要是 0 ,则不是最高位.最后算出的 a1 为 shu a 的最高位。
{
a1--;
}
while(b.x[b1]==0&&b1>0)// b1 为 shu b 的最高位。
{
b1--;
}
int max=a1>b1?a1:b1;// max 为两个最高位的最大值。
for(int i=0;i<=max;i++)// C 每一位都是 a,b 对应位置的和。
{
c.x[i]=a.x[i]+b.x[i];
}
for(int i=0;i<max+1;i++)// 化简 c .
{
while(c.x[i]>=10)//找到一个位置比 10 大,则进位。
{
int k=c.x[i];
c.x[i]=c.x[i]%10;
c.x[i+1]=c.x[i+1]+k/10;
}
}
return c;
}
shu multi(shu a,shu b)// 乘法函数
{
shu c;// C 为最后返回的结果
for(int i=0;i<100;i++)
{
c.x[i]=0;//初始化 C 的每一位。
}
int a1=99,b1=99;//求出输入两个数的位数。
while(a.x[a1]==0)
{
a1--;
}
while(b.x[b1]==0)
{
b1--;
}
int max=a1>b1?a1:b1;//两个输入数的最大位数。
int min=a1>b1?b1:a1;//两个输入数较小的位数。
int sum=max+min;//两个输入数的总位数。
for(int i=0;i<=b1;i++)
{
for(int j=0;j<=a1;j++)
{
c.x[i+j]=c.x[i+j]+b.x[i]*a.x[j];//画出乘法公式找规律,累加c。
}
}
for(int i=0;i<100&&i<sum;i++)//想想一个数乘 99 就知道为什么 i 要小于 sum 了。
{
while(c.x[i]>=10)//大于 10 的那个位置 进位。
{
int k=c.x[i];
c.x[i]=c.x[i]%10;
c.x[i+1]=c.x[i+1]+k/10;
}
}
return c;
}
shu min(shu a,shu b)
{
int a1=99,b1=99;
while(a.x[a1]==0)
{
a1--;
}
while(b.x[b1]==0)
{
b1--;
}
int max=a1>b1?a1:b1;
shu c;
for(int i=0;i<100;i++)
{
c.x[i]=0;
}
for(int i=0;i<=max;i++)
{
c.x[i]=a.x[i]-b.x[i];
}
return c;
}
void output(shu a)
{
int i=99;
while(a.x[i]==0&&i>0)
{
i--;
}
int temp=1;
for(int j=i;j>-1;j--)
{
printf("%d",a.x[j]);
if(temp++==3)
{
temp=1;
printf(",");
}
}
printf("\n");
}
int main()
{
shu a={8,8,8,8,8,8,8,8};//10的意思。高位到低位算的。
shu b={9,9,9,9,9,9,9,9,9};//321的意思。写函数的时候没考虑到这个问题。现在不想改了。
shu c=multi(b,a);
printf("88 888 888 * 999 999 999 =");
output(c);
printf("88 888 888 + 999 999 999 =");
shu d=plus(a,b);
output(d);
return 0;
}
有符号大数的四则运算(接上一题)