我正在使用 Pascal 编写多项式数据类型的作业。我遇到的最大问题是当我尝试使用过程 setCoeff(var p: poly; n: integer; coeff: real) 时,它返回一个新的 poly 对象,其系数仅为索引 n 或 x^n。如何保持其他值不变并使用该程序设置新系数?我出于绝望尝试了很多事情,但这是我使用的两种方法:
procedure setCoeff(var p : poly; n : integer; coeff : real);
{ prints error and halts if n < 0 or n > MAX_DEGREE; setting the coefficient of a term to zero where n >= 0 and n <= MAX_DEGREE will result in that term becoming or remaining non-existent }
var i : integer;
Begin
if n < 0 then
Begin
writeln('Error - illegal coefficient; program halted');
Halt(0);
End;
if n > MAX_DEGREE then
Begin
writeln('Error - illegal coefficient; program halted');
Halt(0);
End;
p[n] := coeff;
End;
End;
-和-
procedure setCoeff(var p : poly; n : integer; coeff : real);
{ prints error and halts if n < 0 or n > MAX_DEGREE; setting the coefficient of a term to zero where n >= 0 and n <= MAX_DEGREE will result in that term becoming or remaining non-existent }
var i : integer;
Begin
if n < 0 then
Begin
writeln('Error - illegal coefficient; program halted');
Halt(0);
End;
if n > MAX_DEGREE then
Begin
writeln('Error - illegal coefficient; program halted');
Halt(0);
End;
p[n] := coeff;
for i := MAX_DEGREE downto 0 do
Begin
getCoeff(p,i,coeff);
if coeff <> 0.0 then
p[i] := coeff;
End;
End;
我知道数组是通过引用传递的,但是每次运行 setCoeff(...) 时似乎都会重置数组的值。这是我的数据类型的顶部,包括它是如何声明的:
unit
polynomial;
interface
uses
Math;
const
MAX_DEGREE = 1000;
type
poly = Array[0..MAX_DEGREE] of Real;
var
coeff: Real;
degree : Integer;