Pascal - 常量



常量是在程序执行期间保持不变的实体。Pascal 只允许声明下列类型的常量:

  • 序数类型
  • 集合类型
  • 指针类型(但仅允许的值是 Nil)。
  • 实际类型
  • 字符
  • 字符串

声明常量

声明常量的语法如下:

const
identifier = constant_value;

下表提供了某些有效常量声明的示例:

实际类型常量

序号 常量类型和示例
1

序数(整数)类型常量

valid_age = 21;

2

集合类型常量

Vowels = set of (A,E,I,O,U);

3

指针类型常量

P = NIL;

4

e = 2.7182818;

velocity_light = 3.0E+10;

5

字符类型常量

Operator = '+';

6

字符串类型常量

president = 'Johnny Depp';

以下示例说明了该概念:

program const_circle (input,output);
const
PI = 3.141592654;

var
r, d, c : real;   {variable declaration: radius, dia, circumference}

begin
   writeln('Enter the radius of the circle');
   readln(r);
   
   d := 2 * r;
   c :=  PI * d;
   writeln('The circumference of the circle is ',c:7:2);
end.

当编译并执行上述代码时,它会产生以下结果:

Enter the radius of the circle
23
The circumference of the circle is 144.51

观察程序输出语句中的格式。变量 c 应以总共 7 位数字和十进制符号后 2 位数字进行格式化。Pascal 允许对数字变量进行这种输出格式化。

© . All rights reserved.