Ada 根据用户输入初始化数组
我从 Java/C++ 转到 Ada,但在弄清楚一些小问题时遇到了困难。是否可以声明一个数组并询问用户最小/最大值然后初始化它?我不喜欢必须为 MIN 和 MAX 定义常量值,似乎应该有一种方法可以做到这一点。
您可以定义不受约束的类型,但仍然必须在程序启动之前在声明块中初始化大小。我是否需要先有包主体,然后是过程声明,然后是实际执行工作的过程中的声明块,如下所示?
PACKAGE BODY Build_Graph IS
TYPE Graph_Box IS ARRAY(Integer RANGE <>, Integer RANGE <>) of Character;
PROCEDURE Print_Graph(Min, Max, Height, Width: IN Integer) IS
BEGIN
DECLARE
Graph: Graph_Box(0..Height, 0..Width);
BEGIN
Do_Stuf(Graph);
END;
END Print_Graph;
END Build_Graph;
I'm coming from Java/C++ to Ada and am having trouble figuring out the small stuff. Is it possible to declare an array and ask the user for the min/max values then initialize it? I don't like having to define constant values for the MIN and MAX and it seems like there should be a way to do this.
You can define an unconstrained type, but you still have to initialize the size in the declare block before your program starts. Would I need to have the package body, then the procedure declaration, then a declare block inside the procedure that actually does the work, like the following?
PACKAGE BODY Build_Graph IS
TYPE Graph_Box IS ARRAY(Integer RANGE <>, Integer RANGE <>) of Character;
PROCEDURE Print_Graph(Min, Max, Height, Width: IN Integer) IS
BEGIN
DECLARE
Graph: Graph_Box(0..Height, 0..Width);
BEGIN
Do_Stuf(Graph);
END;
END Print_Graph;
END Build_Graph;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你在那里展示的应该有效。但是,“声明”块完全没有必要,除非您想捕获数组变量声明或其他内容上的范围异常。我将其更改为:(
我也不喜欢将保留字放在大写字母中。)
我还应该提到的一件事是:Ada 数组不像 cish 语言那样从 0 开始。它们可以,但您也可以将它们从 1 或 -200 或任何您想要的值开始。
我提出这个问题的原因是我看到你定义 Graph_Box 的方式,它实际上是 Height+1 个元素高和 Width+1 个元素宽。您可能不希望这样,因为这很容易让其他人(甚至可能是您)感到困惑。
我的典型习惯用法是从 1 开始数组索引,除非我有充分的理由不这样做。
What you show there should work. However, the "declare" block is totally unnessecary, unless you want to catch range exceptions on the array variable declaration or something. I'd change it to read:
(I also dislike having the reserved words in caps.)
One further thing I should mention: Ada arrays don't have to be 0-based like in cish languages. They can be, but you can also make them start at 1, or -200, or whatever you want.
The reason I bring this up is that I see the way you defined Graph_Box it is actually Height+1 elements high and Width+1 elements wide. You probably don't want that, as it is liable to confuse somebody later (perhaps even you).
My typical idiom is to start my array indices at 1, unless I have some good reason not to.