Задача №12 Урок №18
Primary tabs
Задана последовательность символов, имеющая следующий вид: p1q1p2q2p3...qn–1pn
, где pi
— число, а qi
— знак арифметического действия из набора {+, –, *}. Вычислите значение выражения, предполагая, что действия выполняются согласно правилам арифметики.
Входные данные: На вход программе подается строка указанного вида, состоящая не более чем из 9 чисел, разделенных символами арифметических операций.
Выходные данные: Выведите значение арифметического выражения.
Решение:
var s: string;
function arithmetic (num1,num2: integer; x: string): integer ;
var num: integer;
begin
if x = '*' then
num:= num1 * num2
else if x = '-' then
num:= num1 - num2
else
num:= num1 + num2;
result:= num;
end;
function calculation(s: string): integer;
var i,Code,num,num1, num2, num3: integer;
oper1, oper2,numstr1, numstr2, numstr3: string;
begin
i:= 1;
num1:= 0;
num2:= 0;
num3:= 0;
while (i <= length(s)) do
begin
if (s[i]>= '0') and (s[i] <= '9') then
begin
while (s[i]>= '0') and (s[i] <= '9') do
begin
if (num1 = 0) then
begin
numstr1:= s[i];
inc(i);
end
else if (num2 = 0) then
begin
numstr2:= numstr2 + s[i];
inc(i);
end;
end;
if (numstr2 <> '') then
val(numstr2,num2,Code)
else
val(numstr1,num1,Code) ;
end
else if (oper1 = '') then
begin
oper1:= s[i];
inc(i);
if (oper1 = '*') then
begin
while (s[i]>= '0') and (s[i] <= '9') do
begin
numstr2:= numstr2 + s[i];
inc(i);
end;
val(numstr2,num2,Code);
num1:= arithmetic(num1,num2,oper1);
oper1:= '';
num2:= 0;
numstr2:= '';
end;
end
else if (oper2 = '') then
begin
oper2:= s[i];
inc(i);
if (oper2 = '*') then
begin
while (s[i]>= '0') and (s[i] <= '9') do
begin
numstr3:= numstr3 + s[i];
inc(i);
end;
val(numstr3,num3,Code);
num2:= arithmetic(num3,num2,oper2);
numstr3:= '';
num3:= 0;
oper2:= '';
end
else
begin
num1:= arithmetic(num1,num2,oper1);
numstr2:= '';
num2:= 0;
oper1:= oper2;
oper2:= '';
end;
end;
end;
num:= arithmetic(num1,num2,oper1);
result:= num;
end;
begin
s:= '3*6+7-3*2*5+11';
write(s);
write(' = ',calculation(s));
readln();
end. - Log in to post comments
- 561 reads