您如何 link 将类型的值按顺序转换为整数?
How can you link a type's values sequentially to integers?
我正在尝试开发一个从用户那里获取数字(从 1 - 12)的程序,它将 return 那个月的缩写形式,例如:如果你写 1
它会return JAN
等等
我有以下内容:
type Month_Type is (JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC);
但是我如何 link 这个到 userMonth : Integer;
。我想到了 Month_Type(userMonth) 之类的东西,但这不起作用并给了我错误。我唯一能想到的另一件事是为每个 Month_Type 设置一个循环并在其中设置一个计数器以使其匹配。但这看起来很乱而且效率不高,必须有更好的方法。
在Operations of Discrete Types中,属性'Val
表示一个函数returns一个类型Month_Type
的值,其位置编号等于传递给的参数的值它。例如,表达式 Month_Type'Val(0)
的计算结果为 JAN
.
请注意,属性使用的内部代码不受 Enumeration Representation Clause 的影响。给定一个声明,例如 userMonth : constant := 1
,使用表达式 Month_Type'Val(userMonth - 1)
.
当使用带有 GNAT, the implementation defined attribute 'Enum_Val
denotes a function that "returns the enumeration value whose representation matches the argument." Using the representation clause suggested 的表示子句时,表达式 Month_Type'Enum_Val(userMonth)
将计算为 JAN
,无需调整。
在 Ada 中,您可以更轻松地做到这一点:
with Ada.Text_IO;
procedure Demo is
type Month_Type is (Jan, Feb, Mar, [...], Dec);
package Month_Text_IO is new Ada.Text_IO.Enumeration_IO (Month_Type);
Input : Month_Type;
begin
Month_Text_IO.Get (Input);
end Demo;
无需处理中间的整数值。
作为其他答案的补充,您还可以使用 Ada 表示子句将您的枚举与您喜欢的 intput/output 值相匹配。
如果您需要将您的代码与可能未使用 Ada 编码的其他软件进行交互,这将非常有用。
这有一些限制:如果我的记忆很好,你需要有升序数字。
所以 :
type Month_Type is (JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC);
for Month_Type use (
JAN => 1,
FEB => 2,
...);
我正在尝试开发一个从用户那里获取数字(从 1 - 12)的程序,它将 return 那个月的缩写形式,例如:如果你写 1
它会return JAN
等等
我有以下内容:
type Month_Type is (JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC);
但是我如何 link 这个到 userMonth : Integer;
。我想到了 Month_Type(userMonth) 之类的东西,但这不起作用并给了我错误。我唯一能想到的另一件事是为每个 Month_Type 设置一个循环并在其中设置一个计数器以使其匹配。但这看起来很乱而且效率不高,必须有更好的方法。
在Operations of Discrete Types中,属性'Val
表示一个函数returns一个类型Month_Type
的值,其位置编号等于传递给的参数的值它。例如,表达式 Month_Type'Val(0)
的计算结果为 JAN
.
请注意,属性使用的内部代码不受 Enumeration Representation Clause 的影响。给定一个声明,例如 userMonth : constant := 1
,使用表达式 Month_Type'Val(userMonth - 1)
.
当使用带有 GNAT, the implementation defined attribute 'Enum_Val
denotes a function that "returns the enumeration value whose representation matches the argument." Using the representation clause suggested Month_Type'Enum_Val(userMonth)
将计算为 JAN
,无需调整。
在 Ada 中,您可以更轻松地做到这一点:
with Ada.Text_IO;
procedure Demo is
type Month_Type is (Jan, Feb, Mar, [...], Dec);
package Month_Text_IO is new Ada.Text_IO.Enumeration_IO (Month_Type);
Input : Month_Type;
begin
Month_Text_IO.Get (Input);
end Demo;
无需处理中间的整数值。
作为其他答案的补充,您还可以使用 Ada 表示子句将您的枚举与您喜欢的 intput/output 值相匹配。
如果您需要将您的代码与可能未使用 Ada 编码的其他软件进行交互,这将非常有用。
这有一些限制:如果我的记忆很好,你需要有升序数字。
所以 :
type Month_Type is (JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC);
for Month_Type use (
JAN => 1,
FEB => 2,
...);