📜  Pascal-单位

📅  最后修改于: 2020-11-03 16:21:14             🧑  作者: Mango


Pascal程序可以包含称为单元的模块。一个单元可能由一些代码块组成,这些代码块又由变量和类型声明,语句,过程等组成。Pascal中有许多内置单元,并且Pascal允许程序员定义和编写自己的要使用的单元后来在各种程序中。

使用内置单元

内置单元和用户定义的单元都通过使用子句包含在程序中。我们已经在Pascal-Variants教程中使用了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教程开始时使用的同一程序,编译并运行该程序以查找更改的效果。

创建和使用帕斯卡单位

要创建一个单元,您需要编写要存储在其中的模块或子程序,并将其保存在扩展名为.pas的文件中。该文件的第一行应以关键字unit开头,后跟该单元的名称。例如-

unit calculateArea;

以下是创建Pascal单位的三个重要步骤-

  • 文件名和单元名应该完全相同。因此,我们的单元calculateArea将保存在名为calculateArea.pas的文件中

  • 下一行应包含一个关键字接口。在此行之后,您将编写本单元中所有功能和过程的声明。

  • 在函数声明之后,立即写一个单词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