1

I have a task in my school extraculicular. my task is to create a calculator that can run with 1 input. example, input: 3+7+1*2

and the output will be 12

like that, how to create that? i have search in google to create calculator but all of them show basic tutorial like "Input first number:" "Input second number" "What operator u want" "Result"

Thank's before. My english is not well.

  • 1
    Have a look at http://stackoverflow.com/questions/4589951/parsing-an-arithmetic-expression-and-building-a-tree-from-it-in-java – pavel Jan 27 '16 at 13:27
  • 1
    Using freepascal you have ready to use class for expressions evaluation: [TFPExpressionParser](http://wiki.freepascal.org/How_To_Use_TFPExpressionParser). However it is not the case for homework as I understand :) Start from some theory. For example, [Reverse Polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation) was designed to simplify the calculations and you can find algorithms for converting "normal" infix notation to RPN. Good luck. – Abelisto Jan 27 '16 at 13:56
  • Unit symbolic in the answer below is based on RPN stack evaluation. – Marco van de Voort Sep 05 '20 at 21:27

1 Answers1

2

That is very easy in Free Pascal:

uses symbolic;

var s : string;
begin
  s:='3+7+1*2';
  //readln(s)
  writeln(round(quickevaluate(s,[],[])));
end.

prints

 12

You can read the input expression from the user with readln(s) instead of the fixed expression.

The round is because the evaluation returns a single, for more details see the sources of unit symbolic.

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89