您的位置:首页 > 编程语言 > C语言/C++

POJ1001大数相乘

2012-11-23 14:47 471 查看
需要注意以下几点:

1.把前导0去掉

2.把10000.0000小数点后面的零去掉

3.注意小数点的位置

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int numa[1000]={0};
int numb[1000]={0};
int res[1000000]={0};
int len,lena,lenb;

void mul(int a[],int b[])
{
memset(res,0,sizeof(res));
for (int i=0;i<lena;i++)// the core of big-num-multiply;
{
for (int j=0;j<lenb;j++)
{
res[i+j+1]+=a[i]*b[j];
}
}
lena=lena+lenb;
for (int i=lena-1;i>=0;i--)// process the carry;
{
if (res[i]>9)
{
res[i-1]+=res[i]/10;
res[i]=res[i]%10;
}
}
for (int i=0;i<lena;i++)//store the result ;
{
a[i]=res[i];
}
}

int main()
{
char s[10];
int n;
memset(s,0,sizeof(s));
while(cin>>s>>n)
{
int i,j,dot=-1;
lena=lenb=0;
memset(numa,0,sizeof(numa));
memset(numb,0,sizeof(numb));
for (i=0,j=0;s[i]!=0;i++)
{
if (s[i]=='.')//mark the position of dot;
{
dot=i;
}
else
{
numb[j]=numa[j++]=s[i]-'0';
lena++;
lenb++;
}
}
int len_after_dot=(lena-dot)*n;
for (i=0;i<n-1;i++)//mutiply for n-1 times;
{
mul(numa,numb);
}
i=0;
while(numa[i]==0)//skip the zero in front;
{
if (dot!=-1&&i==lena-len_after_dot)
{
break;
}
i++;
}
int end=lena-1;
if (dot!=-1)
{
while(end>=lena-len_after_dot&&numa[end]==0)//abandon the zero in the back;
{
end--;
}
}
if (dot==-1)
{
for (;i<=end;i++)
{
cout<<numa[i];
}
}
else
{
for (;i<=end;i++)
{
if (i==lena-len_after_dot)
{
cout<<".";
}
cout<<numa[i];
}
}

cout<<endl;
memset(s,0,sizeof(s));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息