Difference between revisions of "Basic Pascal Tutorial/Chapter 1/Constants/bg"

From Lazarus wiki
Jump to navigationJump to search
Line 81: Line 81:
 
За това как да опишете постоянен масив от записи, вижте раздела по-долу.
 
За това как да опишете постоянен масив от записи, вижте раздела по-долу.
  
==Array constants==
+
==Константи-масив==
  
Array constants work much the same as scalar constants, except multiple values can be specified. All of the values must be the same type, whether it is a number (byte, word, integer. real, etc.) or character based (char, string, ansistring, etc.)
+
Константите-масив работят почти по същия начин като обикновените константи, с изключение на това, че могат да бъдат посочени множество стойности. Всички стойности трябва да бъдат от един и същи тип, независимо дали е число (байт, дума, цяло число. Реално и т.н.) или символни (char, низ, ansistring и т.н.).
  
 
===One-dimensional arrays===
 
===One-dimensional arrays===

Revision as of 19:33, 20 April 2021

български (bg) Deutsch (de) English (en) français (fr) italiano (it) 日本語 (ja) 한국어 (ko) русский (ru) 中文(中国大陆)‎ (zh_CN)

 ◄   ▲   ► 

Константи

1C - Constants (author: Tao Yue, state: changed)

Константите се указват чрез идентификатори и получават стойност в началото на програмата. Стойността, съхранявана в константа, не може да бъде променена.

Константите биват три вида: обикновени, записи и масиви. Обикновената константа е идентификатор, на който се присвоява единична стойност. Константата-запис е идентификатор, съдържащ една или повече отделни стойности в структурирана форма. Константата-масив съдържа множество стойности от един тип. Те ще бъдат обяснени подробно в отделни раздели по-долу.

Константа, независимо дали скалар, поле за запис или индекс на масив, може да се използва вместо литерал от същия тип. Тя също така може да се използва навсякъде, където може да се използва и променлива, но с две изключения: не може да се използва отляво на оператор за присвояване и не може да се предава като VAR параметър при извикване на процедура, функция, метод или свойство (property).

Обикновени константи

Обикновените константи се дефинират в секцията Const (constant) на програмата:

const
  Identifier1 = value;
  Identifier2 = value;
  Identifier3 = value;

Например, нека дефинираме някои константи от различни типове данни: низове, символи, цели числа, реални числа и булеви числа. Тези типове данни ще бъдат обяснени допълнително в следващия раздел.

const
  Name = 'Tao Yue';
  FirstLetter = 'a';
  Year = 1997;
  pi = 3.1415926535897932;
  UsingNCSAMosaic = TRUE;

Отбележете, че в Pascal единичните символи са затворени в единични кавички или апострофи (')! Това е различно от по-новите езици, които често използват или позволяват двойни кавички или Heredoc нотация. Стандартният Pascal не използва двойни кавички за указване на символи или низове.

Константите служат за дефиниране на стойност, която се използва в цялата програма, но може да се промени в бъдеще. Вместо да променяте на всички места, в които сте използвали дадената стойност, можете да промените само дефиницията на константата.

Типизираните константи налагат константата да бъде само от определен тип. Например,

const
  a : real = 12;

Ще дефинира константа с идентификатор a, която съдържа реална стойност 12.0 вместо целочислената стойност 12.

Константи-записи

Константите-записи се дефинират чрез създаване на тип запис с едно или повече полета и след това създаване на константа, която се позовава на този тип запис и попълва полетата със стойности.

Общият формат на константите-записи е:

const
identifier: record_type = ( field_values );
identifier

Where

  • identifier е името на константата;
  • record_type е името на типа-запис, който се използва за да опише тази константа;
  • field_values е списък съдържащ име на поле от record_type, две точки (:), стойността за това поле, разделен от следващите поле:стойност с точка и запетая (;).

Нека опитаме прост пример, константа за комплексно число.

type
    complex= record
                R,I: real;
              end;
const
     Pi = 3.14159267;
     C1: Complex = ( R:3; I: 1783.5 );
     C2: complex = ( r: 9.6; I:1.62);
     C3: COMPLEX = ( r:17; i:115);
     C4: complex = ( r:1.9e56; i:72.43);
     C5: Complex=( R: 22.1 ; I: Pi );

Обърнете внимание, че полетата трябва да бъдат инициализирани в същия ред, в който са декларирани (или компилаторът ще сигнализира за грешка). Ако липсва стойност за поле, компилаторът ще предупреди за неинициализирана стойност.

За това как да опишете постоянен масив от записи, вижте раздела по-долу.

Константи-масив

Константите-масив работят почти по същия начин като обикновените константи, с изключение на това, че могат да бъдат посочени множество стойности. Всички стойности трябва да бъдат от един и същи тип, независимо дали е число (байт, дума, цяло число. Реално и т.н.) или символни (char, низ, ansistring и т.н.).

One-dimensional arrays

For one-dimensional array constants the general format is:

const
identifier: array[low_value .. high_value] of type = ( values );
identifier

Where

  • identifier is the name of the array;
  • low_value is the lower bound of the array;
  • high_value is the upper bound of the array;
  • type is the type of value stored in the elements of the array (char, integer, real, string, etc.) and
  • values is a list of values with each item in the list separated from the next item by a comma.

Here's a simple one, the alphabet:

const
  Alphabet: array [1..26] of char =
       ('A','B','C','D','E','F','G','H','I',
        'J','K','L','M','N','O','P','Q','R',
        'S','T','U','V','W','X','Y','Z'   ) ;

There are two rules to remember. As was said before, all the values given have to be of the same type, and you have to specify as many values as there are elements in the array. While the example given above is okay, there will be other parts of the program that reference this array, such as for loops. etc. Instead of using the literal 26 for the size of the array, let's use a scalar constant instead:

Const
   LetterCount = 26;
   Alphabet: array [1..LetterCount] of char =
       ('A','B','C','D','E','F','G','H','I',
        'J','K','L','M','N','O','P','Q','R',
        'S','T','U','V','W','X','Y','Z'   ) ;

Now, any place you need to reference the size of the array, you can just use LetterCount.

Here's a more interesting example in which several data types are used. This example, which is probably from a calendar program, has all sorts of types: char, string, and integer.

Const
  MonthStart = 0 ; // could be 1 and
  MonthEnd   = 11; // 12 if desired
  DayStart   = 0 ; // same,could be 1 and
  DayEnd     = 6;  // 7
  DayNameCh: array [DayStart .. DayEnd] of char =(
        'S','M','T','W','H','F','A');
  DayNameShort: array [DayStart .. DayEnd] of string=
    ( 'Sun','Mon','Tue','Wed','Thu',
      'Fri','Sat' ) ;
  DayNameLong: array DayStart .. DayEnd] of 
    string = ( 'Sunday', 'Monday','Tuesday','Wednesday',
               'Thursday', 'Friday', 'Saturday' );
     MonthNameLong: array[MonthStart ..MonthEnd] of string = (
  'January','February','March','April',
  'May','June','July','August',
  'September','October','November'.
  'December'  
             );
   MonthDays: ARRAY [ MonthStart .. MonthEnd ] of
    integer = ( 31, 28, 31, 30, 31, 30,
                31, 31, 30. 31, 30, 31 );

Notice that for the items indicated as type string, while every value had to be a string, they were not required to all be the same size.

One-dimensional array of record

An array constant may consist of records. To describe them, we use the parentheses ( ) around each record. Using the complex type defined in the section on record constants, we can create a constant array of complex records, as follows:

type
    complex= record
                R,I: real;
              end;
const
     Pi = 3.14159267;
     C2: complex = ( r: 96; I:1.62);
     C_Low = 1;  C_High = 5;
     C: array [ c_low .. c_high] of complex = (
     ( R:3; I:1783.5 ),
     ( r: 96;  I:1.62),
     ( r:17; i:115),
     ( r:1.9e56; i:72.43),
     ( R: 102.1;I: Pi )
     );

As before, values need not be literals; they can be other scalar constants. Also, values must be given in the same order as defined in the record.

Now for a more (pun unintentional) complex example, we use an enumerated type and a set to define a record constant array:

type
    MONTH = ( January, February, March,
              April, May, June,
              July, August, September,
              October, November, December);
    MonthSet = Set of Month;
    EachMonth=Record
         Name, Short: String;
         Count: Integer;
    end;

Const
     Months: array [ January .. December ] of EachMonth = (
       (Name: 'January';  Short: 'Jan'; Count: 31 ),
       (Name: 'February'; Short: 'Feb'; Count: 28 ),
       (Name: 'March';    Short: 'Mar'; Count: 31 ),
       (Name: 'April';    Short: 'Apr'; Count: 30 ),
       (Name: 'May';      Short: 'May'; Count: 31 ),
       (Name: 'June';     Short: 'Jun'; Count: 30 ),
       (Name: 'July';     Short: 'Jul'; Count: 31 ),
       (Name: 'August';   Short: 'Aug'; Count: 31 ),
       (Name: 'September';Short: 'Sep'; Count: 30 ),
       (Name: 'October';  Short: 'Oct'; Count: 31 ),
       (Name: 'November'; Short: 'Nov'; Count: 30 ),
       (Name: 'December'; Short: 'Dec'; Count: 31 )
        );

Take notice of how the items are delimited (separated). Elements in the record are delimited by semi-colons, while commas delimit elements of the array.

Two-dimensional array constant

As used in the example of array of record, two-dimensional arrays are described by encapsulating each of the second dimension in parentheses. To make it easier to understand, the entries in the array have been identified by number, e.g. 13 is the first row, third column, while 21 is the second row, first column. Here is the format:

const
   DemoArray: array [1..2,1..3] of integer =
     (
      (11,12,13),
      (21,22,23)
      );

Three-dimensional array constant

Three-dimensional arrays are rare, and you might never use one, but you should know how to construct a three-dimensional constant array if you need it. Again, each level of array is encapsulated by parentheses. Here is a three-dimensional constant array, and the values represent their position in the array.

const
   Demo3: array [1..2, 1..3, 1..4] of integer=
     (
      (
       (111,112,113,114),
       (121,122,123,124),
       (131,132,133,134)
       ),
      (
       (211,212,213,214),
       (221,222,223,224),
       (231,232,233,234)
      )
     );


 ◄   ▲   ►