Вы находитесь на странице: 1из 2

Example 1: Arithmetic Expression Evaluator

Program EVALUATOR-1 ()
int
r=0, --result
n=0; --number
char op=+, --arithmetic operation
s;
repeat
read(s);
if is_numeric_digit(s) then
n := n*10 + to_number(s);
else
case op of
+: r := r + n;
-: r := r n;
*: r := r * n;
/: r := r div n;
n := 0;
op := s;
until (s = .);
write(r);

- 3 4 * 5 + 1 0 0 / 3 .

op

- 3 4 * 5 + 1 0 0 / 3 .

- 3 4 * 5 + 1 0 0 / 3 .

- 3 4 * 5 + 1 0 0 / 3 .

- 3 4 * 5 + 1 0 0 / 3 .

34

- 3 4 * 5 + 1 0 0 / 3 .

-34

- 3 4 * 5 + 1 0 0 / 3 .

-34

- 3 4 * 5 + 1 0 0 / 3 .

-170

- 3 4 * 5 + 1 0 0 / 3 .

-170

- 3 4 * 5 + 1 0 0 / 3 .

-170

10

- 3 4 * 5 + 1 0 0 / 3 .

-170

100

- 3 4 * 5 + 1 0 0 / 3 .

-70

- 3 4 * 5 + 1 0 0 / 3 .

-70

- 3 4 * 5 + 1 0 0 / 3 .

-23

Example 2: Hierarchical Arithmetic Evaluator


Program EVALUATOR-2 ()
int r=0, --result
f=1, --factor or partial result
n=0; --number
char op1=+, --last + or - operator
op2=*, --last * or / operator
s;
repeat
read(s);
if is_numeric_digit(s) then
n := n*10 + to_number(s);
else if ((s = +) or (s = -)) then
f := (op2 = *) ? (f * n) : (f div n);
r := (op1 = +) ? (r + f) : (r f);
f := 1;
op1 := s;
op2 := *;
else if ((s = *) or (s = /)) then
f := (op2 = *) ? (f * n) : (f div n);
n := 0;
op2 := s;
else
f := (op2 = *) ? (f * n) : (f div n);
r := (op1 = +) ? (r + f) : (r f);
until (s = .);
write(r);

-34*5+100/3.

-34*5+100/3.

op1 op2 s
+

-34*5+100/3.

-34*5+100/3.

-34*5+100/3.

34

-34*5+100/3.

34

-34*5+100/3.

34

- 3 4 * 5 + 1 0 0 / 3 . -170

- 3 4 * 5 + 1 0 0 / 3 . -170

- 3 4 * 5 + 1 0 0 / 3 . -170

10

- 3 4 * 5 + 1 0 0 / 3 . -170

100

- 3 4 * 5 + 1 0 0 / 3 . -170

100

- 3 4 * 5 + 1 0 0 / 3 . -170

100

- 3 4 * 5 + 1 0 0 / 3 . -137

33

Syntactic Analysis of Arithmetic Expressions


-23

-70

-137

-170

-170

-34

-34

34

33

100

34

result number op result | number


op1
+ | - | * | /

result
factor
op1
op2

100

factor op1 result | factor


number op2 factor | number
+ | * | /

Exercises

Program an arithmetic evaluator with nested parentheses.


Test the program with the expression -(34*4+(1-20)/3)+6*4.
Construct the syntactic tree of the above expression.
Construct an algorithm that calculates the real number from a sting
representing a float number (ex. -0.24e1 -2.4).

Вам также может понравиться