Pascal - 常数

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

  • 序数类型

  • 设置类型

  • 指针类型(但唯一允许的值为Nil).

  • 真实类型

  • Char

  • 字符串

声明常量

声明常量的语法如下 :

 
 const 
 identifier = constant_value;

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

实型常量

Sr.No常数类型&示例
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

字符类型常量

运算符='+';

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允许使用数值变量进行这种输出格式化.