Pascal高精度加减乘除代码
时间: 2023-09-26 07:15:21 浏览: 90
高精度 加减乘除 代码
以下是一个示例的Pascal代码,展示了如何实现高精度的加减乘除运算:
```pascal
program HighPrecisionCalc;
uses
SysUtils;
type
BigNumber = array of Integer;
// 将字符串转换为大数表示
function StrToBigNumber(s: string): BigNumber;
var
i: Integer;
begin
SetLength(Result, Length(s));
for i := 1 to Length(s) do
Result[Length(s)-i+1] := Ord(s[i]) - Ord('0');
end;
// 将大数表示转换为字符串
function BigNumberToStr(num: BigNumber): string;
var
i: Integer;
begin
Result := '';
for i := Length(num) downto 1 do
Result := Result + Chr(num[i] + Ord('0'));
end;
// 大数加法
function Add(a, b: BigNumber): BigNumber;
var
carry, i, sum: Integer;
begin
carry := 0;
SetLength(Result, Max(Length(a), Length(b)) + 1);
for i := 0 to Max(Length(a), Length(b)) do
begin
sum := carry;
if i < Length(a) then
sum := sum + a[i];
if i < Length(b) then
sum := sum + b[i];
Result[i] := sum mod 10;
carry := sum div 10;
end;
end;
// 大数减法
function Subtract(a, b: BigNumber): BigNumber;
var
borrow, i, diff: Integer;
begin
borrow := 0;
SetLength(Result, Max(Length(a), Length(b)));
for i := 0 to Max(Length(a), Length(b))-1 do
begin
diff := borrow + a[i];
if i < Length(b) then
diff := diff - b[i];
if diff < 0 then
begin
borrow := -1;
diff := diff + 10;
end
else
borrow := 0;
Result[i] := diff;
end;
end;
// 大数乘法
function Multiply(a, b: BigNumber): BigNumber;
var
i, j, carry, prod: Integer;
begin
SetLength(Result, Length(a) + Length(b));
for i := 0 to Length(a)-1 do
begin
carry := 0;
for j := 0 to Length(b)-1 do
begin
prod := Result[i+j] + a[i] * b[j] + carry;
Result[i+j] := prod mod 10;
carry := prod div 10;
end;
Result[i+Length(b)] := carry;
end;
end;
// 大数除法
function Divide(a: BigNumber; b: Integer): BigNumber;
var
i, remainder, quotient: Integer;
begin
SetLength(Result, Length(a));
remainder := 0;
for i := Length(a)-1 downto 0 do
begin
remainder := remainder * 10 + a[i];
quotient := remainder div b;
remainder := remainder mod b;
Result[i] := quotient;
end;
end;
var
num1, num2: string;
a, b, sum, diff, product, quotient: BigNumber;
divisor: Integer;
begin
Write('输入第一个大数:');
Readln(num1);
Write('输入第二个大数:');
Readln(num2);
Write('输入除数:');
Readln(divisor);
a := StrToBigNumber(num1);
b := StrToBigNumber(num2);
sum := Add(a, b);
diff := Subtract(a, b);
product := Multiply(a, b);
quotient := Divide(a, divisor);
Writeln('加法结果:', BigNumberToStr(sum));
Writeln('减法结果:', BigNumberToStr(diff));
Writeln('乘法结果:', BigNumberToStr(product));
Writeln('除法结果:', BigNumberToStr(quotient));
end.
```
这个示例程序可以实现大数的加减乘除运算。您可以根据自己的需求进行修改和扩展。使用StrToBigNumber函数将字符串转换为大数表示,然后使用Add、Subtract、Multiply和Divide函数进行相应的运算,最后使用BigNumberToStr函数将结果转换回字符串形式输出。
阅读全文