我的 Pascal 代码无法正常工作。问题出在哪里?

My code in Pascal does not want to work correctly. What is the problem in?

我正在编写程序:使用递归函数对实数求和。 它有什么问题?它显示我刚刚输入的数字。

type
 Indexy = 1..100;
 TPoleReal = array [Indexy] of Real;

var
 j: word;
 r, realRes: real;
 tpr: TPoleReal;


function SoucetCisel(n: TPoleReal; j: word): real;
 begin
   if j>0 then begin
     SoucetCisel:=SoucetCisel + n[j];
     j:=j-1;
   end
 end;


begin i:=0; j:=0;
while not seekeof do begin
  read(r); Inc(j);
  tpr[j]:=r;
  writeln(j, ' ', tpr[j]);
end;
realRes:= SoucetCisel(tpr, j);
writeln(realRes);

end.

出于调试目的,我建议您将代码的主要部分简化为

begin
  i:=0;
  j:=0;
  tpr[j] := 1;
  Inc(j);
  tpr[2] := 2;
  realRes:= SoucetCisel(tpr, j);
  writeln(realRes);
end.

这样应该可以更容易地理解问题所在。

您的 SoucetCisel 函数的第一个问题是它实际上不是递归的。

递归函数是用改变的参数调用自身的函数,如 原型阶乘函数

function Factorial(N : Integer)
begin
  if N = 1 then
    Factorial := 1
  else
    Factorial := N * Factorial(N - 1);
end;

这里的递归调用是行

Factorial := Factorial(N - 1);

你的 SoucetCisel 不会那样做,它只是将函数结果的初始值相加 到 n[j] 的值,所以它根本不是递归的。

另一个问题是,如所写,它没有定义的 return 值。在所有的 我遇到过的 Pascal 实现,return 值在进入 函数并保持未定义状态,直到明确为其分配某个值。这 函数结果通常是编译器生成的堆栈上的一些 space 函数的代码保留但最初(在函数的入口处)保存一些随机值,这是由于先前使用堆栈而产生的。

所以,你的 SoucetCisel 函数的结果是有效的

SoucetCisel := ARandomNumber + n[j]

这当然只是另一个随机数。显然,你解决了这个方面 通过确保对函数结果进行显式赋值来实现你的函数 立即进入功能。作为一般规则,通过一个函数的 all 执行路径应该通过一个显式赋值的语句 函数结果的值。

然后,您需要重写它的其余部分,以便它实际上是递归的 按照您的任务要求。

当你在做这两件事时,我建议你使用更多 比匿名 'n' 更有帮助的参数名称。 'n' 通常用来指代无趣的整数。

更新 从你的评论中我不确定它是否应该是认真的。如果是,请考虑这两个函数

function SumOfReals(Reals : TPoleReal; j : word): real;
var
   i : Integer;
begin
  SumOfReals := 0;
  for i := 1 to j do
    SumOfReals := SumOfReals + Reals[i];
end;

function SumOfRealsRecursive(Reals : TPoleReal; j : word): real;
var
  i : Integer;
begin
 SumOfRealsRecursive := Reals[j];
 if j > 1 then
   SumOfRealsRecursive := SumOfRealsRecursive + SumOfRealsRecursive(Reals, j -1);
end;

这两个函数都做同样的事情,即计算内容的总和 直到并包括索引 j 的 Reals 数组。第一个迭代地这样做, 简单地遍历 Reals 数组,第二个以递归方式进行。然而, 很明显递归版本是绝对没有意义的在这种情况下因为 迭代版本做同样的事情但效率更高,因为 它不涉及为每个递归调用复制整个 Reals 数组,而递归版本会这样做。

正如我之前在评论中告诉你的那样。为您的 Pascal 程序尝试此代码:

type
 Indexy = 1..100;
 TPoleReal = array [Indexy] of Real;

var
 j: word;
 r, realRes: real;
 tpr: TPoleReal;


function SoucetCisel(n: TPoleReal; j: word): real;
 begin
   if j>0 then begin
     SoucetCisel:=SoucetCisel(n, j-1) + n[j];
   end
 end;


begin i:=0; j:=0;
while not seekeof do begin
  read(r); Inc(j);
  tpr[j]:=r;
  writeln(j, ' ', tpr[j]);
end;
realRes:= SoucetCisel(tpr, j);
writeln(realRes);

end.