开发手册 欢迎您!
软件开发者资料库

Pascal - 单位

Pascal单位 - 从简单和简单的步骤学习Pascal,从基本到高级概念,包括pascal语法,数据类型,全局和局部变量,单位,函数,循环,常量,结构,数组,枚举,集合,记录,文件,变体记录,指针,链接列表和文本处理。

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

使用内置单位

内置单位和用户定义单位都包含在程序中使用条款.我们已经在 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的文件中.

  • 下一个line应包含单个关键字 interface .在这一行之后,你将编写本单元中所有函数和过程的声明.

  • 在函数声明之后,写下单实施,这又是一个关键字.在包含关键字实现的行之后,提供所有子程序的定义.

以下程序创建名为calculateArea : 的单元;

unit CalculateArea;interfacefunction RectangleArea( length, width: real): real;function CircleArea(radius: real) : real;function TriangleArea( side1, side2, side3: real): real;implementationfunction 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.380Area of Circle with radius 7.0 is: 153.938Area of Triangle 3.0 by 4.0 by 5.0 is: 6.000