I'm trying to do program to basic operations in math. So, I want that the program calculate for example 3*2+4 etc. I already did something, but it needs upgrade. The problem is with division (/). Everything I write it's always the same result- 0. I don't know why. It is also important that the program take into account the brackets.
The point is, that we can input as many brackets, *, /, +, - as we want, and the program do this calculation by priority. We always do * and / first and then + and -. But If we use brackets () we calculate numbers between brackets first.
Example:
We can calculate simple expression:
2*3
3+2
3-2+5
8/4
3*4+1-3
or more complicated:
5+(2-3)+(4-2*5+(1+3))/2
Thanks
program basic_;
{$APPTYPE CONSOLE}
uses
SysUtils,
Math;
type SetCharacters=set of char;
var characters: SetCharacters;
input: string;
o: real;
i: integer;
function brackets(s: string):string;
begin
end;
function basic(input: string): real;
var i,j,k: integer;
r1,r2:real;
r: real; //result
poz, neg: string;
a,b,c: real;
begin
r1:=0;
r2:=0;
i:=0;
c:=0;
while i<length(input) do
begin
i:=i+1;
if (input[i]='(') or (input[i]=')')then
begin
brackets(input);
end;
if (input[i]='*') or (input[i]='/') then
begin
if input[i]='*' then
if input[i+1]='(' then
begin
brackets(input);
end
else
begin
a:=StrToInt(copy(input,pos('*',input)-1,1));
b:=StrToInt(copy(input,pos('*',input)+1,1));
c:=a*b;
end;
end
else //it's not working
if input[i]='/' then
begin
a:=StrToInt(copy(input,pos('/',input)-1,1));
b:=StrToInt(copy(input,pos('/',input)+1,1));
c:=a/b;
writeln(c); readln;
end;
if (input[i]='+') or (input[i]='-') then
begin
if input[i]='+' then
if input[i+1]='(' then
begin
brackets(input);
end
else
begin
poz:=copy(input,i+1,1); //save all positive numbers
j:=1;
while j<= length(poz) do //sum all numbers in array
begin
r1:=r1+StrToInt(poz[j]);
j:=j+1;
end;
end
else
if input[i]='-' then
if input[i+1]='(' then
begin
brackets(input);
end
else
begin
neg:=copy(input,i+1,1); //i save negative numbers
k:=1;
while k<=length(neg) do //i sum all numbers in array
begin
r2:=r2+StrToInt(neg[k]);
k:=k+1;
end;
end;
end;
end;
r:=c+r1-r2;
writeln('Result: ',r:2:2);
readln;
end;
begin
characters:=['e','p','+','-','*','/','!','^','(',')','1','2','3','4','5','6','7','8','9','0'];
write('Input: ');
readln(input);
i:=1;
if input[i] in characters then
begin
o:=basic(input);
end
else
begin
writeln('Error.');
readln;
end
end.