Pascal · lesson 16 of 30 · Data, functions and the command lineGive a value back
A function sets Result. Format puts numbers into a text.
16-functions.pas Download 16-functions.pas
program Functions;
{$mode objfpc}{$H+}
uses
SysUtils;
function Percent(Part, Whole: Double): Integer;
begin
Result := Trunc(Part / Whole * 100);
end;
function Human(Bytes: Double): string;
const
Units: array[0..4] of string = ('B', 'KiB', 'MiB', 'GiB', 'TiB');
var
I: Integer;
begin
I := 0;
while (Bytes >= 1024) and (I < High(Units)) do
begin
Bytes := Bytes / 1024;
Inc(I);
end;
Result := Format('%.1f %s', [Bytes, Units[I]]);
end;
begin
WriteLn(Human(900));
WriteLn(Human(52428800));
WriteLn(Human(8001563222016));
WriteLn(Percent(93, 120), ' percent');
end.
Terminal
$ ./16-functions
900.0 B
50.0 MiB
7.3 TiB
77 percentExercise
Write Max3, which returns the highest of three numbers.