【发布时间】:2013-08-26 20:04:57
【问题描述】:
我试图在 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);
但我无法让它接受它。有什么建议么?提前感谢您的帮助!
【问题讨论】:
-
你根本不能在常量声明中使用函数。
-
编译器不会评估
sqrt。我想,您可以使用类型化常量并在初始化时对其进行修复。您需要几个 VirtualAlloc 调用才能实现。 -
另一种解决方法是使用对常量表达式 (fpc) 不那么挑剔的编译器。
-
@OnTheFly,我不会将更改编译器称为解决方法。
标签: delphi constants definition