如何在数组中使用变量?

LeC*_*oVC 1 pascal freepascal

我正在使用PASCAL进行我正在做的课程而且我在编程时遇到问题,在我的程序中我使用2个数组,它使用来自用户输入的变量但是当我去运行程序时它出现了with,错误:无法计算常量表达式.该数组的代码是:

Var
        x : integer;
        s : array[1..x] of real;
        n : array[1..x] of string[30];
Run Code Online (Sandbox Code Playgroud)

这里x是用户的输入,有没有一种方法可以让数组从1变为x?

Rud*_*uis 6

如果x是变量,那将无法正常工作.所谓的静态数组的范围必须是常量表达式,即必须在编译时知道.

所以你想要的东西不会起作用.

但是在FreePascal中,您可以使用动态数组.它们的长度可以在运行时设置和更改.

var
  x: Integer;
  s: array of Real;
  n: array of string[30]; // why not just string?
Run Code Online (Sandbox Code Playgroud)

然后:

  x := someUserInput(); // pseudo code!
  SetLength(s, x);
  SetLength(n, x);
Run Code Online (Sandbox Code Playgroud)

您应该知道动态数组是0基于的事实,因此您的索引从0最多运行x - 1.但是对于数组的限制,你应该使用Low()High()不是:

  for q := Low(s) to High(s) do
    // access s[q];
Run Code Online (Sandbox Code Playgroud)

(Low()High()不是主题,但我们知道它们也可以用于静态数组,他们返回实际的数组边界-我总是用一高一低这一点)

  • 检测到吸血鬼活动 (2认同)