资源描述:
《pascal-高精度算法》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、高精度算法 加法 减法 乘法 除法一个快速入门的秘诀就是“背”,这个“背”字可以大做文章,想当年我就靠这种方法迅速建立起初步信息学知识体系的。 这是《信息学初学者之家》站长、曾多次参加ACM竞赛并获优异成绩的tenshi所发的切身体会。因此,我们要求,下面的算法不仅要读得懂,而且要熟记于心,这样,你才能在程序设计中灵活地运用……1、高精度加法高精度加法程序如下:programHighPrecision1_Plus;constfn_inp='hp1.inp';fn_out='hp1.out';maxlen=100;{数的最大长度}typehp=recordlen:in
2、teger;{数的长度}s:array[1..maxlen]ofinteger{s[1]为最低位,s[len]为最高位}end;varx:array[1..2]ofhp;y:hp;{x:输入;y:输出}procedurePrintHP(constp:hp);vari:integer;beginfori:=p.lendownto1dowrite(p.s[i]);end;procedureinit;{初始化}varst:string;j,i:integer;beginassign(input,fn_inp);reset(input);forj:=1to2dobeginread
3、ln(st);x[j].len:=length(st);fori:=1tox[j].lendo{将字符串转换到HP}x[j].s[i]:=ord(st[x[j].len+1-i])-ord('0');end;close(input);end;procedurePlus(a,b:hp;varc:hp);{c:=a+b}vari,len:integer;beginfillchar(c,sizeof(c),0);ifa.len>b.lenthenlen:=a.len{从a,b中取较大长度}elselen:=b.len;fori:=1tolendo{从低到高相加}begininc
4、(c.s[i],a.s[i]+b.s[i]);ifc.s[i]>=10thenbegindec(c.s[i],10);{c.s[i]:=c.s[i]-10}inc(c.s[i+1]);{加1到高位}end;end;ifc.s[len+1]>0theninc(len);c.len:=len;end;procedureout;{打印输出}beginassign(output,fn_out);rewrite(output);PrintHP(y);writeln;close(output);end;begininit;Plus(x[1],x[2],y);out;end.2、高精度
5、减法高精度减法程序如下:programHighPrecision2_Subtract;constfn_inp='hp2.inp';fn_out='hp2.out';maxlen=100;{数的最大长度}typehp=recordlen:integer;{数的长度}s:array[1..maxlen]ofinteger{s[1]为最低位,s[len]为最高位}end;varx:array[1..2]ofhp;y:hp;{x:输入;y:输出}positive:boolean;procedurePrintHP(constp:hp);vari:integer;beginfori:
6、=p.lendownto1dowrite(p.s[i]);end;procedureinit;varst:string;j,i:integer;beginassign(input,fn_inp);reset(input);forj:=1to2dobeginreadln(st);x[j].len:=length(st);fori:=1tox[j].lendo{changestringtoHP}x[j].s[i]:=ord(st[x[j].len+1-i])-ord('0');end;close(input);end;procedureSubtract(a,b:hp;varc
7、:hp);{c:=a-b,supposea>=b}vari,len:integer;beginfillchar(c,sizeof(c),0);ifa.len>b.lenthenlen:=a.len{getthebiggerlengthofa,b}elselen:=b.len;fori:=1tolendo{subtractfromlowtohigh}begininc(c.s[i],a.s[i]-b.s[i]);ifc.s[i]<0thenbegininc(c.s[i],10);dec(c.s[i+1]);{add1toahigh