Pascal - 查找元素是否存在于集合中
Pascal - find if element exists in a set
我有这样的代码:
program Project1;
uses crt;
type alph=set of 'A'..'Z';
var mn:alph;
begin
clrscr;
if ('A' in mn) then writeln( 'Yes');
readln;
end.
它不打印任何东西,但会抛出一些问题:
project1.lpr(11,14) 警告:变量 "mn" 似乎没有初始化
不明白为什么,有什么问题吗?
没有,目前没有任何问题。但是,正如警告所说,nm
未初始化。你要么 运行 进入未定义的行为(我不确定这在 Pascal 中是否真的可行)或者代码片段没有任何用处 - 你想检查 mn
是否包含 'A'
,但还没有将任何东西放入 mn
.
宣言
type
Alpha = set of 'A'..'Z';
简单地说 Alpha
是一种允许在 A
和 Z
之间包含零个或多个字母的类型。这并不意味着该类型的变量自动包含该集合的每个元素;它只是意味着该变量将由该范围内的一组字符组成。
var
mn: Alpha; // Uninitialized variable that can contain
// characters between 'A'..'Z'.
begin
mn := ['A'..'Z']; // Valid set of every member
mn := ['A', 'C', 'X']; // Valid set of three members
编译器正确地告诉您您没有为 mn
分配任何值,因此您使用的是未初始化的变量。
顺便说一句,大多数 Pascal 方言的标准约定是在类型前加上 T
以表明它是一种类型。因此,考虑到这一点,这是您发布的包含该更正的代码的工作版本。
program Project1;
uses
crt;
type
TAlpha=set of 'A'..'Z';
var
mn: TAlpha;
begin
clrscr;
mn := ['A'..'Z'];
if ('A' in mn) then
Writeln('A is in mn');
{
My preference to the if statement above - prints true or false
depending on whether the character is in the set, so you get output
either way.
}
WriteLn('A in mn: ', ('A' in mn));
Readln;
end.
解决您的其他问题(来自以下评论):
要检查字符串以查看所有字符是否都是数字 ('0'..'9'),您可以这样做:
function IsNumeric(const str: string): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(str) do
if not (str[i] in ['0'..'9']) then
Result := False;
end;
我有这样的代码:
program Project1;
uses crt;
type alph=set of 'A'..'Z';
var mn:alph;
begin
clrscr;
if ('A' in mn) then writeln( 'Yes');
readln;
end.
它不打印任何东西,但会抛出一些问题: project1.lpr(11,14) 警告:变量 "mn" 似乎没有初始化 不明白为什么,有什么问题吗?
没有,目前没有任何问题。但是,正如警告所说,nm
未初始化。你要么 运行 进入未定义的行为(我不确定这在 Pascal 中是否真的可行)或者代码片段没有任何用处 - 你想检查 mn
是否包含 'A'
,但还没有将任何东西放入 mn
.
宣言
type
Alpha = set of 'A'..'Z';
简单地说 Alpha
是一种允许在 A
和 Z
之间包含零个或多个字母的类型。这并不意味着该类型的变量自动包含该集合的每个元素;它只是意味着该变量将由该范围内的一组字符组成。
var
mn: Alpha; // Uninitialized variable that can contain
// characters between 'A'..'Z'.
begin
mn := ['A'..'Z']; // Valid set of every member
mn := ['A', 'C', 'X']; // Valid set of three members
编译器正确地告诉您您没有为 mn
分配任何值,因此您使用的是未初始化的变量。
顺便说一句,大多数 Pascal 方言的标准约定是在类型前加上 T
以表明它是一种类型。因此,考虑到这一点,这是您发布的包含该更正的代码的工作版本。
program Project1;
uses
crt;
type
TAlpha=set of 'A'..'Z';
var
mn: TAlpha;
begin
clrscr;
mn := ['A'..'Z'];
if ('A' in mn) then
Writeln('A is in mn');
{
My preference to the if statement above - prints true or false
depending on whether the character is in the set, so you get output
either way.
}
WriteLn('A in mn: ', ('A' in mn));
Readln;
end.
解决您的其他问题(来自以下评论):
要检查字符串以查看所有字符是否都是数字 ('0'..'9'),您可以这样做:
function IsNumeric(const str: string): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(str) do
if not (str[i] in ['0'..'9']) then
Result := False;
end;