NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 23 of 30 · Files and errors · bonusBuild a calculator

Put Split, TryStrToFloat and case into one program.

Programming on the NAS › Pascal in 30 lessons

23-calculator.pas Download 23-calculator.pas

program Calculator;
{$mode objfpc}{$H+}
uses
  SysUtils;
var
  Line: string;
  Part: TStringArray;
  A, B: Double;
begin
  WriteLn('Type a sum like 12 * 4. An empty line ends.');
  repeat
    Write('> ');
    ReadLn(Line);
    if Trim(Line) = '' then
      Break;
    Part := Trim(Line).Split([' '], TStringSplitOptions.ExcludeEmpty);
    if (Length(Part) <> 3) or not TryStrToFloat(Part[0], A) or not TryStrToFloat(Part[2], B) then
    begin
      WriteLn('Type number, sign, number with spaces');
      Continue;
    end;
    case Part[1] of
      '+': WriteLn(A + B:0:2);
      '-': WriteLn(A - B:0:2);
      '*': WriteLn(A * B:0:2);
      '/':
        if B = 0 then
          WriteLn('You cannot divide by zero')
        else
          WriteLn(A / B:0:2);
    else
      WriteLn('Signs: + - * /');
    end;
  until False;
  WriteLn('Bye');
end.

Terminal

$ ./23-calculator
Type a sum like 12 * 4. An empty line ends.
> 12 * 4
48.00
> 7 / 2
3.50
> 5 / 0
You cannot divide by zero
> five * 2
Type number, sign, number with spaces
> 
Bye

Exercise

Keep the last result and let the user type r for it.