加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Delphi中定义常量时出错

发布时间:2020-12-15 04:03:31 所属栏目:大数据 来源:网络整理
导读:我试图在Delphi(Delphi 2005)中定义一个基于其他常量的const,但是Delphi抱怨它不是一个常量表达式.这就是我的代码: program myProgram;const Xpoints = 20; Ypoints = 30; ArraySize = trunc(sqrt(Xpoints*Ypoints));var myArray : array[1..ArraySize] of
我试图在Delphi(Delphi 2005)中定义一个基于其他常量的const,但是Delphi抱怨它不是一个常量表达式.这就是我的代码:
program myProgram;

const
  Xpoints = 20;
  Ypoints = 30;
  ArraySize = trunc(sqrt(Xpoints*Ypoints));

var
  myArray : array[1..ArraySize] of integer;

我可以做ArraySize = Xpoints * Ypoints,但sqrt会导致问题.我的想法是,我希望通过常量Xpoints和Ypoints来调整数组的大小.我可以这样做:

program myProgram;

const
  sqrtXpoints = 4.472135956;
  sqrtYpoints = 5.47722557506;
  Xpoints = trunc(sqrtXpoints*sqrtXpoints);
  Ypoints = trunc(sqrtYpoints*sqrtYpoints);
  ArraySize = trunc(sqrtXpoints*sqrtYpoints);

var
  myArray : array[1..ArraySize] of integer;

注意稍微高估trunc的平方根值.如果我改变sqrtXpoints或sqrtYpoints,一切都会正确更新,但这种方法看起来很……愚蠢.

作为临时修复,我可以像这样评估常量:

program myProgram;

const
  Xpoints = 20;
  Ypoints = 30;
  ArraySize = 24;

var
  myArray : array[1..ArraySize] of integer;

但我不喜欢这个,因为如果我更改Xpoints或Ypoints,ArraySize不会自动更新.

看起来编译器应该知道如何在编译时评估一个常量定义为另一个常量的数学函数,如上例所示,甚至更简单的事情:

const
  pi = 4.0*arctan(1.0);

但我无法接受它.有什么建议?在此先感谢您的帮助!

解决方法

Delphi不允许在常量定义中使用大多数函数.
但是您可以轻松解决它,只需使用动态数组,您就可以从代码中计算出您想要的所有内容:
const
  Xpoints = 20;
  Ypoints = 30;
var
  myArray : array of integer;

procedure TForm9.FormCreate(Sender: TObject);
begin
  setlength(myArray,trunc(sqrt(Xpoints*Ypoints)));

end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读