资源简介 高精度加法program exam1;constmax=200;vara,b,c:array[1..max] of 0..9;n:string;lena,lenb,lenc,i,x:integer;beginwrite('Input augend:'); readln(n);lena:=length(n); {加数放入a数组}for i:=1 to lena do a[lena-i+1]:=ord(n[i])-ord('0');write('Input addend:'); readln(n);lenb:=length(n); {被加数放入b数组}for i:=1 to lenb do b[lenb-i+1]:=ord(n[i])-ord('0');i:=1;while (i<=lena) or(i<=lenb) do beginx := a[i] + b[i] + x div 10; {两数相加,然后加前次进位}c[i] := x mod 10; {保存第i位的值}i := i + 1end;if x>=10 then {处理最高进位}begin lenc:=i;c[i]:=1 endelse lenc:=i-1;for i:=lenc downto 1 do write(c[i]); {输出结果}writelnend.例2 高精度减法。从键盘读入两个正整数,求它们的差。分析:类似加法,可以用竖式求减法。在做减法运算时,需要注意的是:被减数必须比减数大,同时需要处理借位。因此,可以写出如下关系式if a[i]c[i]:=a[i]-b[i]类似,高精度减法的参考程序:program exam2;constmax=200;vara,b,c:array[1..max] of 0..9;n,n1,n2:string;lena,lenb,lenc,i,x:integer;beginwrite('Input minuend:'); readln(n1);write('Input subtrahend:'); readln(n2);{处理被减数和减数}if (length(n1)beginn:=n1;n1:=n2;n2:=n;write('-') {n1end;lena:=length(n1); lenb:=length(n2);for i:=1 to lena do a[lena-i+1]:=ord(n1[i])-ord('0');for i:=1 to lenb do b[lenb-i+1]:=ord(n2[i])-ord('0');i:=1;while (i<=lena) or(i<=lenb) do beginx := a[i] - b[i] + 10 + x; {不考虑大小问题,先往高位借10}c[i] := x mod 10 ; {保存第i位的值}x := x div 10 - 1; {将高位借掉的1减去}i := i + 1end;lenc:=i;while (c[lenc]=0) and (lenc>1) do dec(lenc); {最高位的0不输出}for i:=lenc downto 1 do write(c[i]);writelnend.例3 高精度乘法。从键盘读入两个正整数,求它们的积。分析:类似加法,可以用竖式求乘法。在做乘法运算时,同样也有进位,同时对每一位进乘法运算时,必须进行错位相加,如图3, 图4。分析C数组下标的变化规律,可以写出如下关系式C i = C’ i +C ”i +…由此可见,C i跟A[i]*B[j]乘积有关,跟上次的进位有关,还跟原C i的值有关,分析下标规律,有x:= A[i]*B[j]+ x DIV 10+ C[i+j-1];C[i+j-1] := x mod 10;类似,高精度乘法的参考程序:program exam3;constmax=200;vara,b,c:array[1..max] of 0..9;n1,n2:string;lena,lenb,lenc,i,j,x:integer;beginwrite('Input multiplier:'); readln(n1);write('Input multiplicand:'); readln(n2);lena:=length(n1); lenb:=length(n2);for i:=1 to lena do a[lena-i+1]:=ord(n1[i])-ord('0');for i:=1 to lenb do b[lenb-i+1]:=ord(n2[i])-ord('0');for i:=1 to lena do beginx:=0;for j:=1 to lenb do begin {对乘数的每一位进行处理}x := a[i]*b[j] + x div 10 + c[i+j-1]; {当前乘积+上次乘积进位+原数}c[i+j-1] := x mod 10;end;c[i+j]:= x div 10; {进位}end;lenc:=i+j;while (c[lenc]=0) and (lenc>1) do dec(lenc);for i:=lenc downto 1 do write(c[i]);writelnend.例4 高精度除法。从键盘读入两个正整数,求它们的商(做整除)。分析:做除法时,每一次上商的值都在0~9,每次求得的余数连接以后的若干位得到新的被除数,继续做除法。因此,在做高精度除法时,要涉及到乘法运算和减法运算,还有移位处理。当然,为了程序简洁,可以避免高精度乘法,用0~9次循环减法取代得到商的值。这里,我们讨论一下高精度数除以单精度数的结果,采取的方法是按位相除法。参考程序:program exam4;constmax=200;vara,c:array[1..max] of 0..9;x,b:longint;n1,n2:string;lena:integer;code,i,j:integer;beginwrite('Input dividend:'); readln(n1);write('Input divisor:'); readln(n2);lena:=length(n1);for i:=1 to lena do a[i] := ord(n1[i]) - ord('0');val(n2,b,code);{按位相除}x:=0;for i:=1 to lena do beginc[i]:=(x*10+a[i]) div b;x:=(x*10+a[i]) mod b;end;{显示商}j:=1;while (c[j]=0) and (jfor i:=j to lena do write(c[i]) ;writelnend.实质上,在做两个高精度运算时候,存储高精度数的数组元素可以不仅仅只保留一个数字,而采取保留多位数(例如一个整型或长整型数据等),这样,在做运算(特别是乘法运算)时,可以减少很多操作次数。 展开更多...... 收起↑ 资源预览