函数总是 returns a 0

Function always returns a 0

我有点困惑为什么加法函数总是 returns 0 无论我放置什么输入组合。我已经检查过用户输入是否正确放置在我制作的数组中,并且输入中没有任何问题。我构造函数的方式是否有任何错误?

Program MathOperation;
uses crt;

type
inputArray = array [1..5] of real;
var
userChoice : integer;
inputValue : inputArray;

procedure userInputValues;
var
counter : integer = 0;
begin
    while counter<5 do
    begin
        write('>> Enter number [', counter + 1, ']: ');
        read(inputValue[counter]);
        counter := counter+1;
    end;
end;

function addOp:real;
var
addCtr : integer = 0;
sum : real = 0;
begin
     while addCtr<5 do
     begin
         sum := sum + inputValue[addCtr];
         addCtr := addCtr+1;
     end
end; 

您的 AddOp 函数始终 returns 0 因为您从未为其函数结果赋值。在其中的某处,您应该有一个 保证* 执行的语句,如下所示:

  AddOp := {whatever the correct value is}

由于您显然使用的是 FreePascal,因此您可以使用 Result 作为函数结果的别名,如

  Result := {whatever the correct value is}

*实际上,这有点夸大其词,因为通过函数代码的有效执行路径可能不止一条,所以更通用的规则是通过函数的每条有效执行路径都应该使函数return一个值。