首先,我要声明这里的乘是指高精度与低精度相乘,除是高精度除以低精度
1,其实乘法与加法类似,差别就在于carry可能是两位数以上,其余与我上篇博客加法代码一致。
2,除法主要是要传入三个参数,被除数和除数以及高精度最高位与除数相除所得的余数。
下面献上代码
#include<iostream>
#include<string.h>
using namespace std;
struct beg
{
int d[1000];
int len;
beg()
{
memset(d,0,sizeof(d));
len=0;
}
};
beg change(char str[]);
beg mul(beg a,int b);
beg div(beg a,int b,int &r);
void show(beg c);
int main()
{
char str1[1000];
gets(str1);
int b;
cin>>b;
beg a;
a=change(str1);
beg c;
c=mul(a,b);
show(c);
int r=a.d[a.len-1]%b; //先求出第一个r
c=div(a,b,r);
show(c);
return 0;
}
beg change(char str[])
{
beg a;
a.len=strlen(str);
for(int i=0;i<a.len;i++)
{
a.d[i]=str[a.len-i-1]-'0';
}
return a;
}
//高精度乘以低精度
beg mul(beg a,int b)
{
beg c;
int carry=0;
for(int i=0;i<a.len;i++)
{
int temp=a.d[i]*b+carry;
c.d[c.len++]=temp%10;
carry=temp/10;
}
while(carry!=0) //乘法进位情况可能不止一位,故用while
{
c.d[c.len++]=carry%10;
carry=carry/10;
}
return c;
}
//高精度除以低精度
beg div(beg a,int b,int &r) //r是先用高精度的最高位除以低精度所得的余数
{
beg c;
c.len=a.len;
for(int i=a.len-1;i>=0;i--)
{
r=r*10+a.d[i];
if(r<b) c.d[i]=0;
else
{
c.d[i]=r/b;
r=r%b;
}
}
while(c.len-1>=1&&c.d[c.len-1]==0) //防止最高为出现0
{
c.len--;
}
return c;
}
void show(beg c)
{
for(int i=c.len-1;i>=0;i--)
{
cout<<c.d[i];
}
cout<<endl;
}
感谢小伙伴们的阅读!