Вычисление арифметичиских выражений с целыми числами
Primary tabs
(Решение задачи №9 урока 17)
Эта функция вычислит выражение в строке expression:
function calculateExpression(expression: string): integer;
var
currentNum: string;
i, sum, product, code, currentInt: integer;
sign, addSign: char;
begin
sum := 0;
product := 1;
currentNum := '0';
addSign := '+';
expression += '+';
for i := 1 to length(expression) do
begin
if (expression[i] >= '0') and (expression[i] <= '9') then
currentNum += expression[i]
else
begin
val(currentNum, currentInt, code);
currentNum := '0';
sign := expression[i];
product *= currentInt;
if (sign = '+') OR (sign = '-') then
begin
case addSign of
'+': sum += product;
'-': sum -= product;
end;
product := 1;
addSign := sign
end;
end;
end;
calculateExpression := sum;
end;
Пример строки:
5+92-15+75*53+76-21+5+92-15+75*53+76-21+5+92-15
- Log in to post comments
- 1629 reads