LearnStanmorephysics

Grade 10 · Delphi Foundations

Maths functions & Random

Grade 10 · Data & calculations · Lesson and coding task · about 12 minutes

Open this task in the Delphi workspace →

Delphi ships with a toolbox of maths functions you will use constantly:

FunctionDoesExample
Round(r)nearest whole numberRound(7.65) = 8
Trunc(r)chops the decimals offTrunc(7.65) = 7
Sqrt(x)square rootSqrt(16) = 4
Sqr(x)x squaredSqr(5) = 25
Abs(x)absolute valueAbs(-3) = 3
Random(n)random 0 … n-1Random(6) gives 0..5

Because Random(6) gives 0 to 5, a dice roll needs + 1:

Randomize;                 // shuffle the generator (once)
iDice := Random(6) + 1;    // 1..6
Exam tip. "A random number from 10 to 99" is a favourite: Random(90) + 10. Work it out as Random(how-many-possibilities) + lowest.
Delphi secret: banker's rounding. When the decimal part is exactly .5, Delphi's Round goes to the nearest EVEN number: Round(2.5) = 2 but Round(3.5) = 4. This surprises everyone once. We behave exactly the same — try it! (For always-up rounding of money, calculate with FloatToStrF or Trunc(r + 0.5).)

What you will do

Hints
  1. Round and Trunc both give Integers, so wrap them in IntToStr to join them into the caption.
  2. Random(6) gives 0..5 — add 1 to get 1..6.
  3. The memo line is 'You rolled a ' + IntToStr(iDice)
Model solution
procedure TfrmMaths.btnRoundClick(Sender: TObject);
var
  rAmount : Real;
begin
  rAmount := StrToFloat(edtAmount.Text);
  lblRound.Caption := 'Round: ' + IntToStr(Round(rAmount)) + ' | Trunc: ' + IntToStr(Trunc(rAmount));
end;

procedure TfrmMaths.btnDiceClick(Sender: TObject);
var
  iDice : Integer;
begin
  Randomize;
  iDice := Random(6) + 1;
  memOutput.Lines.Add('You rolled a ' + IntToStr(iDice));
end;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.