我怎麼正確地寫:?如何檢查數組是否包含特定值?
If number is different from Array[1] to Array[x-1] the begin......
其中number是一個整數,數組是整數數組從1到x
我怎麼正確地寫:?如何檢查數組是否包含特定值?
If number is different from Array[1] to Array[x-1] the begin......
其中number是一個整數,數組是整數數組從1到x
我相信你想要做的事,如果number
未找到數組。然後,你可以做這樣的:
NoMatch := true;
for i := Low(MyArray) to High(MyArray) do
if MyArray[i] = number then
begin
NoMatch := false;
break;
end;
if NoMatch then
DoYourThing;
您可以創建一個數字是不是在陣列發現檢查功能。然後,您可以在每次需要執行此檢查時使用此功能。每一次,代碼都會更具可讀性。例如,你可以做這樣的:
function IsNumberInArray(const ANumber: integer;
const AArray: array of integer): boolean;
var
i: integer;
begin
for i := Low(AArray) to High(AArray) do
if ANumber = AArray[i] then
Exit(true);
result := false;
end;
...
if not IsNumberInArray(number, MyArray) then
DoYourThing;
如果使用的是舊版本的Delphi,你必須begin result := true; break; end
更換Exit(true)
。在Delphi的新版本中,我想你也可以玩類似泛型的東西。
偉大的思想家想象:D –
@Jens除了你的代碼與Andreas' –
我確定我建議你不要使用基於1的數組索引。請允許我重複這個建議。 –
另外,'Array'在Delphi中不是一個有效的變量名。 –
@AndreasRejbrand我已經告訴過菲利普,至少有一次之前:http://stackoverflow.com/questions/29594762/program-stops-after-reading-procedure-delphi –