这是代码,我不认为Read1d过程有错误,但是每次执行这个程序时,它都显示数组所有元素的值为0。我的错误在哪里?
Program MainProgram;
Uses Crt;
Const
n = 100;
Type
TypeIn = 1..n;
Array1d = Array[TypeIn] Of Integer;
Procedure Read1d(Var Tai: TypeIn; X: Array1d);
Var
i: TypeIn;
Begin
Writeln('Enter the size of the array: ');
Readln(Tai);
For i := 1 To Tai Do
Begin
Write('X[', i, '] = ');
Read(X[i]);
End;
End;
Procedure Write1d(Var Tai: TypeIn; X: Array1d);
Var
i: TypeIn;
Begin
Write(' | ');
For i := 1 To Tai Do
Begin
Write(X[i], ' | ');
End;
WriteLn;
End;
Function Nbev(Tai:TypeIn; X: Array1d ; V:Integer):Integer;
var i, cpt:Integer;
Begin
cpt := 0;
for i := 1 to tai do
Begin
if X[i] = V then
cpt := cpt + 1;
End;
Nbev := cpt;
End;
Function RechV(Tai: TypeIn; X: Array1d; V: Integer): Boolean;
Var
i: TypeIn; //Result: Boolean;
Begin
Result := False;
For i := 1 To Tai Do
Begin
If X[i] = V Then
Begin
Result := True;
Break;
End;
End;
RechV := Result;
End;
Var
Tai: TypeIn;
X: Array1d;
V: Integer;
Begin
textcolor(green);
textbackground(black);
ClrScr;
Read1d(Tai, X);
WriteLn;
Write1d(Tai, X);
Writeln('What''s the element you are looking for: ');
Readln(V);
If RechV(Tai, X, V) Then
Begin
Writeln('Element found.');
WriteLn(Nbev(Tai, X, V));
End
Else
Writeln('Element not found.');
End.
我试图输入 Array1d 数组的每个元素的值,写下所有元素,然后给出允许在最多 100 个整数的数组中找到给定值 V 的解决方案。下面的测试将解释我的情况。
我预料到了这个:
Enter the size of the array:
4
X[1] = 1
X[2] = 2
X[3] = 3
X[4] = 4
| 1 | 2 | 3 | 4 |
What's the element you are looking for:
4
Element found.
我明白了:
Enter the size of the array:
4
X[1] = 1
X[2] = 2
X[3] = 3
X[4] = 4
| 0 | 0 | 0 | 0 |
What's the element you are looking for:
4
Element not found.
我应该做什么来修复它?
“通过引用”进行论证
Procedure Read1d(Var Tai: TypeIn; var X: Array1d);
否则你的过程会创建数组的副本,因为它是“按值”参数,并且你填充数组的本地副本而不是全局实例