我一直在尝试运行以下程序,但编译器一直告诉我标识符n
不起作用。程序应该做的是执行n的值,即过程文件的次数。 n
不能是常量,因为在运行时读取。
有人可以帮帮我吗?
Program num;
Var
f:Text;
b,g:array [1..n] of integer;
m,n:Integer;
c:String[1];
Procedure thenum (a:array [1..n] of integer);
Begin
for i:= 1 to n do
repeat
Read (f,a[i]);
Write(a[i]);
Until(a[i]=' ');
End;
End;
Procedure sth ( j:array [1..n] of integer);
begin
for k:= 1 to n do
while not seekEoln and eof(f) do
begin
read(f,j[k]);
Write(j[k]);
end;
End;
End;
procedure space;
begin
Read(f,c);
Write(c);
end;
procedure file
begin
Assign(f,'textfile.txt');
Reset(f);
thenum (b[a]);
space;
sth (g[k]);
Close(f);
Readln;
End;
Begin
Assign(f,'textfile.txt');
Reset(f);
repeat
Read (f,n);
Write(n);
Until(n=' ');
End;
Read(f,c);
Write(c);
while not seekEoln and eof(f) do
begin
read(f,m);
Write(m);
end;
file;
End.
答案 0 :(得分:0)
编译器在编译时不知道n
的值。通常,您可以将一些适当的最大大小定义为常量,例如N_MAX
,然后将其用于您的数组维度。在运行时,您将确保n <= N_MAX
。
答案 1 :(得分:0)
Pascal不支持声明为固定长度的可变大小的数组。
大多数现代编译器(Delphi / FreePascal)都支持动态数组,其中长度是在运行时设置的。下限始终为零,上限为length - 1:
var
Arr: array of Integer;
L, H, Len: Integer;
ArraySize: Integer;
begin
Len := 10; // Value of Len can be input at runtime
SetLength(Arr, Len);
L := Low(Arr); // Will be 0
H := High(Arr); // Will be Len - 1, because first index is 0
ArrSize := Length(Arr); // Will be Len
WriteLn('Low: ', L, ' High: ', H, ' Length: ', ArrSize);
ReadLn;
end;
这是一个完整的示例(在Delphi中,但它应该与FreePascal一起使用)接受来自控制台的输入并使用它来设置长度,并显示如上所述的低,高和长度值。它还演示了如何将数组传递给不了解数组中元素数量的过程。
program Project1;
uses
SysUtils;
// Lists the items in an array to the console without
// knowing in advance the size of the array
procedure ListAnArray(const TheArray: array of Integer);
var
x: Integer;
begin
// Retrieve the valid low and high indexes, and
// loop through the array to output each value
for x := Low(TheArray) to High(TheArray) do
WriteLn('TheArray ', x, ' value: ', TheArray[x]);
end;
// The variables we'll be using (a few more than I would
// normally use, just to make the example clearer)
var
ArraySize: Integer; // Length of array input by user
lowIdx, highIdx: Integer; // low array index, high index
ArrayLen: Integer; // Length of array (set at runtime)
Counter: Integer; // Loop counter
TestArray: array of Integer; // Our dynamic array
begin
Write('Enter array length: '); // Prompt user
Readln(ArraySize); // Read input
Writeln('You entered: ', ArraySize);
WriteLn(''); // Blank line separator
SetLength(TestArray, ArraySize); // Size the array
lowIdx := Low(TestArray); // Get low index (always 0)
highIdx := High(TestArray); // # of elements - 1
ArrayLen := Length(TestArray); // Same as user entered
Writeln('Low: ', lowIdx, // Output what we've learned
' High: ', highIdx,
' Length: ', ArrayLen);
WriteLn(''); // Blank line separator
for Counter := lowIdx to highIdx do // Fill the array with values
TestArray[Counter] := Counter * Counter;
ListAnArray(TestArray); // Pass array to procedure
WriteLn(''); // Blank line separator
WriteLn('Press Enter to quit...'); // Pause to allow reading.
Readln;
end.