rmeeh04

textcalculator v2.0 alpha

Jan 15th, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.23 KB | Source Code | 0 0
  1. program textcalculator;
  2.  
  3. uses
  4.   SysUtils; // Required for string operations and conversions.
  5.  
  6. var
  7.   input: string;
  8.   num1, num2, result: Real;
  9.   op: Char;
  10.  
  11. begin
  12.   WriteLn('Welcome to the Text-Based Calculator!');
  13.   WriteLn('Enter an expression (e.g., 2 + 5, 10 / 2):');
  14.   WriteLn('Operators supported: + (add), - (subtract), * (multiply), / (divide)');
  15.   WriteLn('Type "exit" to quit.');
  16.  
  17.   repeat
  18.     Write('> ');
  19.     ReadLn(input);
  20.  
  21.     // Exit the program if user types "exit"
  22.     if LowerCase(input) = 'exit' then
  23.       Break;
  24.  
  25.     try
  26.       // Find the operator in the input string
  27.       if Pos('+', input) > 0 then
  28.         op := '+'
  29.       else if Pos('-', input) > 0 then
  30.         op := '-'
  31.       else if Pos('*', input) > 0 then
  32.         op := '*'
  33.       else if Pos('/', input) > 0 then
  34.         op := '/'
  35.       else
  36.         raise Exception.Create('Invalid operator! Use +, -, *, or /.');
  37.  
  38.       // Split the input into two numbers based on the operator
  39.       case op of
  40.         '+': begin
  41.           num1 := StrToFloat(Trim(Copy(input, 1, Pos('+', input) - 1)));
  42.           num2 := StrToFloat(Trim(Copy(input, Pos('+', input) + 1, Length(input))));
  43.           result := num1 + num2;
  44.         end;
  45.         '-': begin
  46.           num1 := StrToFloat(Trim(Copy(input, 1, Pos('-', input) - 1)));
  47.           num2 := StrToFloat(Trim(Copy(input, Pos('-', input) + 1, Length(input))));
  48.           result := num1 - num2;
  49.         end;
  50.         '*': begin
  51.           num1 := StrToFloat(Trim(Copy(input, 1, Pos('*', input) - 1)));
  52.           num2 := StrToFloat(Trim(Copy(input, Pos('*', input) + 1, Length(input))));
  53.           result := num1 * num2;
  54.         end;
  55.         '/': begin
  56.           num1 := StrToFloat(Trim(Copy(input, 1, Pos('/', input) - 1)));
  57.           num2 := StrToFloat(Trim(Copy(input, Pos('/', input) + 1, Length(input))));
  58.           if num2 = 0 then
  59.             raise Exception.Create('Error: Division by zero is not allowed!');
  60.           result := num1 / num2;
  61.         end;
  62.       end;
  63.  
  64.       // Output the result
  65.       WriteLn('Result: ', result:0:2);
  66.     except
  67.       on E: Exception do
  68.         WriteLn('Error: ', E.Message);
  69.     end;
  70.  
  71.   until False;
  72.  
  73.   WriteLn('Thank you for using the calculator!');
  74. end.
  75.  
Advertisement
Add Comment
Please, Sign In to add comment