Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program textcalculator;
- uses
- SysUtils; // Required for string operations and conversions.
- var
- input: string;
- num1, num2, result: Real;
- op: Char;
- begin
- WriteLn('Welcome to the Text-Based Calculator!');
- WriteLn('Enter an expression (e.g., 2 + 5, 10 / 2):');
- WriteLn('Operators supported: + (add), - (subtract), * (multiply), / (divide)');
- WriteLn('Type "exit" to quit.');
- repeat
- Write('> ');
- ReadLn(input);
- // Exit the program if user types "exit"
- if LowerCase(input) = 'exit' then
- Break;
- try
- // Find the operator in the input string
- if Pos('+', input) > 0 then
- op := '+'
- else if Pos('-', input) > 0 then
- op := '-'
- else if Pos('*', input) > 0 then
- op := '*'
- else if Pos('/', input) > 0 then
- op := '/'
- else
- raise Exception.Create('Invalid operator! Use +, -, *, or /.');
- // Split the input into two numbers based on the operator
- case op of
- '+': begin
- num1 := StrToFloat(Trim(Copy(input, 1, Pos('+', input) - 1)));
- num2 := StrToFloat(Trim(Copy(input, Pos('+', input) + 1, Length(input))));
- result := num1 + num2;
- end;
- '-': begin
- num1 := StrToFloat(Trim(Copy(input, 1, Pos('-', input) - 1)));
- num2 := StrToFloat(Trim(Copy(input, Pos('-', input) + 1, Length(input))));
- result := num1 - num2;
- end;
- '*': begin
- num1 := StrToFloat(Trim(Copy(input, 1, Pos('*', input) - 1)));
- num2 := StrToFloat(Trim(Copy(input, Pos('*', input) + 1, Length(input))));
- result := num1 * num2;
- end;
- '/': begin
- num1 := StrToFloat(Trim(Copy(input, 1, Pos('/', input) - 1)));
- num2 := StrToFloat(Trim(Copy(input, Pos('/', input) + 1, Length(input))));
- if num2 = 0 then
- raise Exception.Create('Error: Division by zero is not allowed!');
- result := num1 / num2;
- end;
- end;
- // Output the result
- WriteLn('Result: ', result:0:2);
- except
- on E: Exception do
- WriteLn('Error: ', E.Message);
- end;
- until False;
- WriteLn('Thank you for using the calculator!');
- end.
Advertisement
Add Comment
Please, Sign In to add comment