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:
| Function | Does | Example |
|---|---|---|
| Round(r) | nearest whole number | Round(7.65) = 8 |
| Trunc(r) | chops the decimals off | Trunc(7.65) = 7 |
| Sqrt(x) | square root | Sqrt(16) = 4 |
| Sqr(x) | x squared | Sqr(5) = 25 |
| Abs(x) | absolute value | Abs(-3) = 3 |
| Random(n) | random 0 … n-1 | Random(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
- btnRound: read a Real from edtAmount and show both Round and Trunc of it on lblRound, e.g. Round: 8 | Trunc: 7
- btnDice: roll a dice with Random(6) + 1 and add a memo line: You rolled a 4
Hints
- Round and Trunc both give Integers, so wrap them in IntToStr to join them into the caption.
- Random(6) gives 0..5 — add 1 to get 1..6.
- 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;