☰ Contents · Computing

Changing the data type and a test

Lessons 49–50 · 2 lessons · N. I. Taylaqov (general editor), A. B. Akhmedov, M. D. Pardayeva, A. A. Abdug‘aniyev, U. M. Mirsanov. Informatics and Information Technologies, Grade 10, 1st edition. “Extremum-Press”, Tashkent, 2017
49

Changing the data type

Textbook: pp. 106–110
GoalDistinguishes the data types (Integer, Real, String), changes the type with StrToInt, IntToStr, StrToFloat and FloatToStr and declares local variables inside a procedure.
New words
StrToInt: converts a text string to an integer · StrToIntStrToFloat: converts a text string to a real number · StrToFloatlocal variable: a variable declared in a procedure and usable only there · lokal o‘zgaruvchivar: the section where variables and their types are declared · var
Explanation

A number in an Edit is really text, so it must be converted to a number before calculating: Delphi does not allow an expression of one type to be given directly to a variable of another type. StrToInt (text to number) and IntToStr (number to text) are used for integers, StrToFloat and FloatToStr for real numbers. Intermediate results of a calculation are stored in variables: they are declared in the var section under the procedure header, for example var r: Real; or var i, m, n, s: Integer; Such a variable is local: it works only inside this procedure and disappears when the procedure ends. If a letter is typed in an Edit instead of a number, or a real number uses the wrong separator (a comma instead of a point or the other way round), StrToInt and StrToFloat show an error message, so tell the user in a Label how to type. FloatToStr gives the result with the separator of the computer settings.

Worked examples
A cube: Edit1 holds the edge length a. procedure TForm1.Button1Click(Sender: TObject); ⏎ var a: Integer; ⏎ begin ⏎  a := StrToInt(Edit1.Text); ⏎  Label1.Caption := 'Hajm: ' + IntToStr(a * a * a); ⏎  Label2.Caption := 'Sirt: ' + IntToStr(6 * a * a); ⏎ end; With a = 4: Hajm: 64, Sirt: 96.
A factorial: procedure TForm1.Button2Click(Sender: TObject); ⏎ var i, n, f: Integer; ⏎ begin ⏎  n := StrToInt(Edit2.Text); ⏎  f := 1; ⏎  for i := 1 to n do ⏎    f := f * i; ⏎  Label3.Caption := 'Faktorial: ' + IntToStr(f); ⏎ end; With n = 6: 1·2·3·4·5·6 = 720; Faktorial: 720. The Integer type holds numbers up to 2 147 483 647, so n should not exceed 12 (13! is too big). For a circle use r := StrToFloat(Edit1.Text); FloatToStr(Pi * r * r) – Pi is a ready constant.
Class activity

“The calculator”: a pair builds an application with two Edits; a button shows the sum, difference and product in three Labels; they test what message the application gives for a wrong entry.

Practice
1
Which function converts text to an integer?
2
If a = 5, what is 6 * a * a?
3
For n = 5, what is f at the end with f := f * i (f starts at 1, i = 1..n)?
4
Why can a local variable not be used in another procedure?