Menu

[r47]: / trunk / docscript / tex / math / expression.cpp  Maximize  Restore  History

Download this file

81 lines (66 with data), 1.3 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
class Input;
double expression(Input&);
double term(Input&);
double factor(Input&);
using namespace std;
class Input {
char const *ch;
public:
int operator()() { return *ch; }
Input& next() { ++ch; return *this; }
Input(char const *ch): ch(ch) {}
};
double expression(Input& input)
{
double value = term(input);
while ( 1 )
if ( input() == '+' )
value += term(input.next());
else if ( input() == '-' )
value -= term(input.next());
else
break;
return value;
}
double term(Input& input)
{
double value = factor(input);
while ( 1 )
if ( input() == '*' )
value *= factor(input.next());
else if ( input() == '/' )
value /= factor(input.next());
else
break;
return value;
}
double factor(Input& input)
{
double value;
if ( isdigit(input()) )
value = input()-'0', input.next();
else if ( input() == '(' ) {
value = expression(input.next());
if ( input() == ')' )
input.next();
else
throw "')' expected"; }
else
throw "unexpectd character";
return value;
}
int main(int argc, char *argv[])
{
try {
while ( *++argv ) {
Input input(*argv);
cout << *argv << '=' << expression(input) << endl;
}
}
catch ( const char* exception ) {
cerr << "Error: " << exception << endl;
return 1;
}
return 0;
}
MongoDB Logo MongoDB