Pascal - 單元



一個 Pascal 程式可以由稱為單元的模組組成。一個單元可能包含一些程式碼塊,而程式碼塊又由變數和型別宣告、語句、過程等組成。Pascal 中有許多內建單元,並且 Pascal 允許程式設計師定義和編寫他們自己的單元,以便以後在各種程式中使用。

使用內建單元

內建單元和使用者定義單元都透過 uses 子句包含在程式中。我們已經在Pascal - 變體教程中使用了 variants 單元。本教程解釋瞭如何建立和包含使用者定義的單元。但是,讓我們首先看看如何在程式中包含內建單元crt

program myprog;
uses crt;

以下示例說明了如何使用crt單元:

Program Calculate_Area (input, output);
uses crt;
var 
   a, b, c, s, area: real;

begin
   textbackground(white); (* gives a white background *)
   clrscr; (*clears the screen *)
   
   textcolor(green); (* text color is green *)
   gotoxy(30, 4); (* takes the pointer to the 4th line and 30th column) 
   
   writeln('This program calculates area of a triangle:');
   writeln('Area = area = sqrt(s(s-a)(s-b)(s-c))');
   writeln('S stands for semi-perimeter');
   writeln('a, b, c are sides of the triangle');
   writeln('Press any key when you are ready');
   
   readkey;
   clrscr;
   gotoxy(20,3);
   
   write('Enter a: ');
   readln(a);
   gotoxy(20,5);
   
   write('Enter b:');
   readln(b);
   gotoxy(20, 7);
   
   write('Enter c: ');
   readln(c);

   s := (a + b + c)/2.0;
   area := sqrt(s * (s - a)*(s-b)*(s-c));
   gotoxy(20, 9);
   
   writeln('Area: ',area:10:3);
   readkey;
end.

這與我們在 Pascal 教程開始時使用的程式相同,編譯並執行它以瞭解更改的效果。

建立和使用 Pascal 單元

要建立一個單元,您需要編寫要儲存在其中的模組或子程式,並將其儲存在副檔名為.pas的檔案中。此檔案的首行應以關鍵字 unit 開頭,後跟單元的名稱。例如:

unit calculateArea;

以下是建立 Pascal 單元的三個重要步驟:

  • 檔名稱和單元名稱應完全相同。因此,我們的單元calculateArea將儲存在名為calculateArea.pas的檔案中。

  • 下一行應包含單個關鍵字interface。在此行之後,您將編寫所有將在該單元中出現的函式和過程的宣告。

  • 在函式宣告之後,寫下單詞implementation,它也是一個關鍵字。在包含關鍵字 implementation 的行之後,提供所有子程式的定義。

以下程式建立名為 calculateArea 的單元:

unit CalculateArea;
interface

function RectangleArea( length, width: real): real;
function CircleArea(radius: real) : real;
function TriangleArea( side1, side2, side3: real): real;

implementation

function RectangleArea( length, width: real): real;
begin
   RectangleArea := length * width;
end;

function CircleArea(radius: real) : real;
const
   PI = 3.14159;
begin
   CircleArea := PI * radius * radius;
end;

function TriangleArea( side1, side2, side3: real): real;
var
   s, area: real;

begin
   s := (side1 + side2 + side3)/2.0;
   area := sqrt(s * (s - side1)*(s-side2)*(s-side3));
   TriangleArea := area;
end;

end.

接下來,讓我們編寫一個簡單的程式來使用我們上面定義的單元:

program AreaCalculation;
uses CalculateArea,crt;

var
   l, w, r, a, b, c, area: real;

begin
   clrscr;
   l := 5.4;
   w := 4.7;
   area := RectangleArea(l, w);
   writeln('Area of Rectangle 5.4 x 4.7 is: ', area:7:3);

   r:= 7.0;
   area:= CircleArea(r);
   writeln('Area of Circle with radius 7.0 is: ', area:7:3);

   a := 3.0;
   b:= 4.0;
   c:= 5.0;
  
   area:= TriangleArea(a, b, c);
   writeln('Area of Triangle 3.0 by 4.0 by 5.0 is: ', area:7:3);
end.

當編譯並執行上述程式碼時,它會產生以下結果:

Area of Rectangle 5.4 x 4.7 is: 25.380
Area of Circle with radius 7.0 is: 153.938
Area of Triangle 3.0 by 4.0 by 5.0 is: 6.000
廣告