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 允許對數字變數進行這種輸出格式化。