您的位置:首页 > 其它

poj 1001 Exponentiation

2014-09-22 19:04 253 查看
Description
Problemsinvolvingthecomputationofexactvaluesofverylargemagnitudeandprecisionarecommon.Forexample,thecomputationofthenationaldebtisataxingexperienceformanycomputersystems.

ThisproblemrequiresthatyouwriteaprogramtocomputetheexactvalueofRnwhereRisarealnumber(0.0<R<99.999)andnisanintegersuchthat0<n<=25.

Input
TheinputwillconsistofasetofpairsofvaluesforRandn.TheRvaluewilloccupycolumns1through6,andthenvaluewillbeincolumns8and9.
Output
TheoutputwillconsistofonelineforeachlineofinputgivingtheexactvalueofR^n.Leadingzerosshouldbesuppressedintheoutput.Insignificanttrailingzerosmustnotbeprinted.Don'tprintthedecimalpointifthe
resultisaninteger.
SampleInput
95.12312
0.432120
5.123415
6.75929
98.99910
1.010012

SampleOutput
548815620517731830194541.899025343415715973535967221869852721
.00000005148554641076956121994511276767154838481760200726351203835429763013462401
43992025569.928573701266488041146654993318703707511666295476720493953024
29448126.764121021618164430206909037173276672
90429072743629540498.107596019456651774561044010001
1.126825030131969720661201

Hint
Ifyoudon'tknowhowtodeterminewheatherencountedtheendofinput:

sisastringandnisaninteger

C++

while(cin>>s>>n)

{

...

}

c

while(scanf("%s%d",s,&n)==2)//toseeifthescanfreadinasmanyitemsasyouwant

/*while(scanf(%s%d",s,&n)!=EOF)//thisalsowork*/

{

...

}


数据输入非常规格,底数严格就6位,指数是1-20之间的整数,我们先将底数化为整数,同时记下小数的位数,进行幂运算,最后结果再处理小数的位数。

在将小数化为整数的时候要逆向存储,multi函数可以当做模板来计算整数相乘。


#include<iostream>
#include<string.h>
#include<string>
usingnamespacestd;
intn,a[201]={0},b[201]={0},lena,lenb;//n是指数,a和b数组是用来存储底数的,lena是a的长度,lenb是b的长度
voidmulti()
{
inti,j,k,c[201];//数组c是用来过渡的
for(k=1;k<=n-1;k++)//一共进行n-1次乘法
{
memset(c,0,sizeof(c));
for(i=0;i<lena;i++)
for(j=0;j<lenb;j++)
{
c[i+j]=c[i+j]+a[i]*b[j];
c[i+j+1]=c[i+j+1]+c[i+j]/10;
c[i+j]=c[i+j]%10;
}
for(i=0;i<=200;i++)//将中间结果赋给数组a,即a是用来保存最终结果的
a[i]=c[i];
lena=lena+lenb;
}
}
intmain()
{
stringR;
while(cin>>R>>n)//输入数据
{
intlen=6;//底数的长度一定是6
intdot=-1,i,j,up=0,down=-1;//dot是小数点的位置,up是最终结果的上界,down是下界
memset(a,0,sizeof(a));//每次都要归0处理
memset(b,0,sizeof(b));
for(i=5;R[i]=='0';i--)//将底数数值后面无关紧要的0去掉
len--;
for(i=len-1,j=0;i>=0;i--,j++)//将底数逆序存储在数组a和b中,同时保存小数点所在的位置
{
if(R[i]!='.')
{a[j]=R[i]-'0';b[j]=R[i]-'0';}
else
{dot=i;j--;}
}
if(dot==-1)dot=0;//dot=-1说明底数是个整数
elsedot=len-dot-1;//否则计算小数的位数
lena=lenb=len;
multi();//调用函数
for(i=200;a[i]==0;i--)//计算上界
up=i;
up--;
for(i=0;a[i]==0;i++)//计算下界
down=i;
down++;
if(dot==0)//没有小数,即结果是整数的话就直接输出
{
for(i=up;i>=0;i--)
cout<<a[i];
cout<<endl;
}
else
{
dot=dot*n-1;//计算总小数的位数
i=up;
if(up<dot)i=dot;//小数位数很大,举例0.00000123
j=down;
if(dot<down)j=dot;//小数位数很小,举例123000
for(;i>=j;i--)//逆序输出
{
if(i==dot)cout<<".";
cout<<a[i];
}
cout<<endl;
}
}
return0;
}







                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: