如何为整数数组赋值? [英] How do I assign a value to a whole array of integers?

查看:201
本文介绍了如何为整数数组赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以这样做:

const
  arrayOfIntegers : Array[1..15] of Integer = (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);

但是我该怎么做呢?

var
  arrayOfIntegers : Array[1..15] of Integer;
begin
  arrayOfIntegers := (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);
end;

一旦我尝试编译上面的代码,我得到E2029')'预期但','发现

As soon as I try to compile the code above I get E2029 ')' expected but ',' found

推荐答案

典型用法如下:

type
  TIntegerArray1to15 = Array[1..15] of Integer;
const
  INIT_INT_1_15_ARRAY: TIntegerArray1to15 = (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);

var
  arrayOfIntegers : TIntegerArray1to15;
begin
  arrayOfIntegers := INIT_INT_1_15_ARRAY;
  .... use and update arrayOfIntegers[]
end;

在这种情况下,您应该更好地定义自己的类型(代码不会更慢或更大,您将能够在此类型的实例之间进行分配)。你会确保你的数组边界将按预期(1..15)。

You should better define your own type in this case (code won't be slower or bigger, and you'll be able to make assignments between instances of this type). And you'll ensure that your array boundaries will be as expected (1..15).

const 语句将被编译为reference数组,它将被复制到您的 arrayOfIntegers 局部变量中。我已经把它写成大写,在声明常量(但不是强制性 - 这只是一个个人品味)时有一些常用的用法。

The const statement will be compiled as a "reference" array, which will be copied in your arrayOfIntegers local variable. I've made it uppercase, which a somewhat commmon usage when declaring constants (but not mandatory - this is just a personal taste).

如果你希望你的代码是更通用和可重用(如果你想成为一个懒惰的程序员,那么IMHO是有意义的),你可以依靠动态数组和/或 const 参数(如果您的数组从索引0开始)。

If you want your code to be more generic and reusable (which IMHO makes sense if you want to be a lazy programmer) you may rely on dynamic arrays, and/or array of const parameters (if your array start with index 0).

这篇关于如何为整数数组赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆