Menu

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

Download this file

111 lines (95 with data), 2.0 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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
#include <cctype>
#include <iostream>
class Input;
double expression(Input&);
double term(Input&);
double factor(Input&);
using namespace std;
class Input {
char const *ch;
int current;
double num;
public:
enum { Number = 256 };
int operator()() { return current; }
double number() { return num; }
Input& next();
Input(char const *ch): ch(ch) { next(); }
};
Input& Input::next() {
while ( isspace(*ch) )
++ch;
if ( isdigit(*ch) ) {
num = *ch++ - '0';
while ( isdigit(*ch) )
num = num * 10 + (*ch++ - '0');
current = Number;
}
else switch ( *ch ) {
case '+': current = *ch++; break;
case '-': current = *ch++; break;
case '*': current = *ch++; break;
case '/': current = *ch++; break;
case '(': current = *ch++; break;
case ')': current = *ch++; break;
case '\0': current = *ch; break;
default:
throw "invalid character";
}
return *this;
}
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 ( input() == Input::Number )
value = input.number(), input.next();
else if ( input() == '-' )
value = - expression(input.next());
else if ( input() == '(' ) {
value = expression(input.next());
if ( input() == ')' )
input.next();
else
throw "')' expected"; }
else
throw "factor expected";
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