Pascal - 将数组作为子程序参数传递

Pascal 允许将数组作为子程序参数传递。 以下函数将采用数组作为参数并返回通过数组传递的数字的平均值,如下所示 −

program arrayToFunction;
const
   size = 5;
type
   a = array [1..size] of integer;
var
   balance:  a = (1000, 2, 3, 17, 50);
   average: real;  

function avg( var arr: a) : real;
var
   i :1..size;
   sum: integer;

begin
   sum := 0;
   for i := 1 to size do
      sum := sum + arr[i];
   avg := sum / size;
end;

begin  
   (*  Passing the array to the function  *)
   average := avg( balance ) ;
   
   (* output the returned value *)
   writeln( 'Average value is: ', average:7:2);
end.

当上面的代码被编译并执行时,会产生以下结果 −

Average value is: 214.40

❮ pascal_arrays.html