Сообщение от nikkka
как его включить? (dev c++)
А вот этого уже не знаю. С этой IDE не работал.
Добавлено через 1 минуту
Если мыслить логически, то эта команда должна быть в меню Debug (если оно конечно же есть).
Добавлено через 14 часов 26 минут
В продолжение темы калькулятора.
Добавил константы (Pi и e) и функции (max, min, sin, cos, asin, acos, tan, atan, exp (возведение e в степень), lg, ln, log (соответственно логарифм по основанию 10, e и по произвольному основанию), rad, degr (перевод соответсвенно из градусов в радианы и обратно), sqrt). Параметры функции задаются в скобках через запятую.
Добавил унарный оператор "," (запятая) с минимальным приоритетом для корректного разбора функций, аргументы которых необходимо предварительно вычислить.
Изменил иерархию классов.
token.h
C++ | 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
| #ifndef TOKEN_H
#define TOKEN_H
namespace my
{
// Тип лексемы
enum token_type
{
t_operand,
t_operator,
t_function,
t_bracket
};
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс - лексема ////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class token
{
public:
token(token_type type);
virtual ~token() = 0;
token_type type() const;
protected:
const token_type m_type;
};
};
#endif |
|
token.cpp
C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| #include "token.h"
namespace my
{
token::token(token_type type)
: m_type(type)
{
}
token::~token()
{
}
token_type token::type() const
{
return m_type;
}
}; |
|
functions_and_operands.h
C++ | 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
| #ifndef FUNCTIONS_AND_OPERATORS_H
#define FUNCTIONS_AND_OPERATORS_H
#include "token.h"
#include <string>
#include <stack>
namespace my
{
// Арность оператора
enum arity
{
unary = 1,
binary
};
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления операторов и функций ///////////////////
///////////////////////////////////////////////////////////////////////////
class functions_and_operators
: public token
{
public:
functions_and_operators(token_type type, arity ar, const std::string& name);
// Вычисление значения оператора/функции
// Количество изъятых из стека операндов определяется арностью оператора/функции
virtual void operator () (std::stack<token*>& stk) const = 0;
~functions_and_operators() = 0;
protected:
void throwError(const std::string& msg) const;
const arity m_arity;
const std::string m_name;
};
};
#endif |
|
functions_and_operands.cpp
C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #include "functions_and_operators.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления операторов и функций ///////////////////
///////////////////////////////////////////////////////////////////////////
functions_and_operators::functions_and_operators(token_type type, arity ar, const std::string& name)
: token(type), m_arity(ar), m_name(name)
{
}
functions_and_operators::~functions_and_operators()
{
}
void functions_and_operators::throwError(const std::string& msg) const
{
throw(std::runtime_error("\'" + m_name + "\': " + msg));
}
}; |
|
functions.h
C++ | 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
| #ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include "functions_and_operators.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления функций ////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class functions
: public functions_and_operators
{
public:
functions(arity ar, const std::string& name);
~functions() = 0;
};
///////////////////////////////////////////////////////////////////////////
// Функция max ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class max
: public functions
{
public:
max();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция min ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class min
: public functions
{
public:
min();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция sin ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class sin
: public functions
{
public:
sin();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция cos ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class cos
: public functions
{
public:
cos();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция asin ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class asin
: public functions
{
public:
asin();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция acos ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class acos
: public functions
{
public:
acos();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция tan ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class tan
: public functions
{
public:
tan();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция atan ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class atan
: public functions
{
public:
atan();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция exp ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class exp
: public functions
{
public:
exp();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция ln (натуральный логарифм) //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class ln
: public functions
{
public:
ln();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция lg (десятичный логарифм) ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class lg
: public functions
{
public:
lg();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция log(a, base) (логарифм числа a по основанию base ) /////////////
///////////////////////////////////////////////////////////////////////////
class log
: public functions
{
public:
log();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция abs ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class abs
: public functions
{
public:
abs();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция rad (пересчет из градусов в радианы) ///////////////////////////
///////////////////////////////////////////////////////////////////////////
class rad
: public functions
{
public:
rad();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция degr (пересчет из радиан в градусы) ////////////////////////////
///////////////////////////////////////////////////////////////////////////
class degr
: public functions
{
public:
degr();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Функция sqrt ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class sqrt
: public functions
{
public:
sqrt();
void operator () (std::stack<token*>& stk) const;
};
};
#endif |
|
functions.cpp
C++ | 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
| #include "functions.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include "operand.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления функций ////////////////////////////////
///////////////////////////////////////////////////////////////////////////
functions::functions(arity ar, const std::string& name)
: functions_and_operators(t_function, ar, name)
{
}
functions::~functions()
{
}
///////////////////////////////////////////////////////////////////////////
// Функция max ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
max::max()
: functions(binary, "Function max(a, b)")
{
}
void max::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
delete op1;
delete op2;
stk.push(new operand(std::max(val1, val2)));
}
///////////////////////////////////////////////////////////////////////////
// Функция min ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
min::min()
: functions(binary, "Function min(a, b)")
{
}
void min::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
delete op1;
delete op2;
stk.push(new operand(std::min(val1, val2)));
}
///////////////////////////////////////////////////////////////////////////
// Функция sin ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
sin::sin()
: functions(unary, "Function sin(a)")
{
}
void sin::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::sin(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция cos ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
cos::cos()
: functions(unary, "Function cos(a)")
{
}
void cos::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::cos(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция asin ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
asin::asin()
: functions(unary, "Function asin(a)")
{
}
void asin::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
if(std::abs(val1) > 1)
throwError("argument must be less or equal to 1");
delete op1;
stk.push(new operand(std::asin(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция acos ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
acos::acos()
: functions(unary, "Function acos(a)")
{
}
void acos::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
if(std::abs(val1) > 1)
throwError("argument must be less or equal to 1");
delete op1;
stk.push(new operand(std::acos(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция tan ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
tan::tan()
: functions(unary, "Function tan(a)")
{
}
void tan::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::tan(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция atan ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
atan::atan()
: functions(unary, "Function atan(a)")
{
}
void atan::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::atan(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция exp ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
exp::exp()
: functions(unary, "Function exp(a)")
{
}
void exp::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::exp(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция ln (натуральный логарифм) //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
ln::ln()
: functions(unary, "Function ln(a)")
{
}
void ln::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
if(val1 <= 0)
throw(std::runtime_error("invalid argument"));
delete op1;
stk.push(new operand(std::log(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция lg (десятичный логарифм) ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
lg::lg()
: functions(unary, "Function lg(a)")
{
}
void lg::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
if(val1 <= 0)
throw(std::runtime_error("invalid argument"));
delete op1;
stk.push(new operand(std::log10(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция log(a, base) (логарифм числа a по основанию base ) /////////////
///////////////////////////////////////////////////////////////////////////
log::log()
: functions(binary, "Function log(a, base)")
{
}
void log::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
if(val1 <= 0)
throwError("invalid argument");
if((val2 == 1) || (val2 <= 0))
throwError("invalid base");
delete op1;
delete op2;
double result = std::log(val1) / std::log(val2);
stk.push(new operand(result));
}
///////////////////////////////////////////////////////////////////////////
// Функция abs ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
abs::abs()
: functions(unary, "Function abs(a)")
{
}
void abs::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(std::abs(val1)));
}
///////////////////////////////////////////////////////////////////////////
// Функция rad (пересчет из градусов в радианы) ///////////////////////////
///////////////////////////////////////////////////////////////////////////
rad::rad()
: functions(unary, "Function rad(a)")
{
}
void rad::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(M_PI / 180.0 * val1));
}
///////////////////////////////////////////////////////////////////////////
// Функция degr (пересчет из радиан в градусы) ////////////////////////////
///////////////////////////////////////////////////////////////////////////
degr::degr()
: functions(unary, "Function degr(a)")
{
}
void degr::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
delete op1;
stk.push(new operand(180 / M_PI * val1));
}
///////////////////////////////////////////////////////////////////////////
// Функция sqrt ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
sqrt::sqrt()
: functions(unary, "Function sqrt(a)")
{
}
void sqrt::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value();
if(val1 < 0)
throwError("invalid operand");
delete op1;
stk.push(new operand(std::sqrt(val1)));
}
}; |
|
operators.h
C++ | 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
| #ifndef OPERATORS_H
#define OPERATORS_H
#include "functions_and_operators.h"
namespace my
{
//Приоритет оператора
enum priority
{
pr0,
pr1,
pr2,
pr3,
pr4
};
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления операторов /////////////////////////////
///////////////////////////////////////////////////////////////////////////
class operators
: public functions_and_operators
{
public:
operators(arity ar, priority pr, const std::string& name);
// Приоритет оператора
virtual priority prior() const;
~operators() = 0;
protected:
const priority m_priority;
};
///////////////////////////////////////////////////////////////////////////
// Оператор вычисления факториала /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class factorial
: public operators
{
public:
factorial();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор '+' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class plus
: public operators
{
public:
plus();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор '*' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class mult
: public operators
{
public:
mult();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор '/' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class divide
: public operators
{
public:
divide();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор '-' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class minus
: public operators
{
public:
minus();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор '^' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class power
: public operators
{
public:
power();
void operator () (std::stack<token*>& stk) const;
};
///////////////////////////////////////////////////////////////////////////
// Оператор ',' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class comma
: public operators
{
public:
comma();
void operator () (std::stack<token*>& stk) const;
};
};
#endif |
|
operators.cpp
C++ | 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
| #include "operators.h"
#include <iostream>
#include "operand.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Абстрактный класс представления операторов /////////////////////////////
///////////////////////////////////////////////////////////////////////////
operators::operators(arity ar, priority pr, const std::string& name)
: functions_and_operators(t_operator, ar, name), m_priority(pr)
{
}
priority operators::prior() const
{
return m_priority;
}
operators::~operators()
{
}
///////////////////////////////////////////////////////////////////////////
// Оператор вычисления факториала /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
factorial::factorial()
: operators(unary, pr4, "Operator !")
{
}
void factorial::operator () (std::stack<token*>& stk) const
{
if(stk.empty())
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op = dynamic_cast<operand*>(stk.top());
stk.pop();
double temp = op->value();
delete op;
if((ceil(temp) != temp) || (temp <= 0))
throwError("Invalid argument");
if(temp > 20)
std::cerr << "Operator !: type overflow" << std::endl;
size_t val = static_cast<size_t>(temp);
double result = 1;
while(val)
result *= val--;
stk.push(new operand(result));
}
///////////////////////////////////////////////////////////////////////////
// Оператор '+' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
plus::plus()
: operators(binary, pr1, "Operator +")
{
}
void plus::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
delete op1;
delete op2;
stk.push(new operand(val1 + val2));
}
///////////////////////////////////////////////////////////////////////////
// Оператор '*' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
mult::mult()
: operators(binary, pr2, "Operator *")
{
}
void mult::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
delete op1;
delete op2;
stk.push(new operand(val1 * val2));
}
///////////////////////////////////////////////////////////////////////////
// Оператор '/' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
divide::divide()
: operators(binary, pr2, "Operator /")
{
}
void divide::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
if(val2 == 0)
throwError("error dividing by zero");
delete op1;
delete op2;
stk.push(new operand(val1 / val2));
}
///////////////////////////////////////////////////////////////////////////
// Оператор '-' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
minus::minus()
: operators(binary, pr1, "Operator -")
{
}
void minus::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
delete op1;
delete op2;
stk.push(new operand(val1 - val2));
}
///////////////////////////////////////////////////////////////////////////
// Оператор '^' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
power::power()
: operators(binary, pr3, "Operator ^")
{
}
void power::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op2 = dynamic_cast<operand*>(stk.top());
stk.pop();
if(stk.top()->type() != t_operand)
throwError("expected an operand");
operand* op1 = dynamic_cast<operand*>(stk.top());
stk.pop();
double val1 = op1->value(), val2 = op2->value();
if((val1 < 0) || (fabs(val2) < 1))
throwError("the result is undefined");
delete op1;
delete op2;
stk.push(new operand(pow(val1, val2)));
}
///////////////////////////////////////////////////////////////////////////
// Оператор ',' ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
comma::comma()
: operators(unary, pr0, "Operator ,")
{
}
void comma::operator () (std::stack<token*>& stk) const
{
size_t opCnt = m_arity;
if(stk.size() < opCnt)
throwError("not enough parameters");
if(stk.top()->type() != t_operand)
throwError("expected an operand");
}
}; |
|
operand.h
C++ | 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
| #ifndef OPERAND_H
#define OPERAND_H
#include "token.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Класс представления операнда ///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
class operand
: public token
{
public:
operand(double val)
: token(t_operand), m_value(val)
{
}
~operand()
{
}
double value() const
{
return m_value;
}
private:
operand();
const double m_value; // Значение операнда
};
};
#endif |
|
calculator.h
C++ | 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
| #ifndef CALCULATOR_H
#define CALCULATOR_H
#include <stack>
#include <string>
#include <queue>
#include "operators.h"
namespace my
{
///////////////////////////////////////////////////////////////////////////
// Класс, предоставляющий интерфейс для вычислений ////////////////////////
///////////////////////////////////////////////////////////////////////////
class calculator
{
public:
// В конструкторе происходит перевод из инфиксной в постфиксную нотацию
calculator(const std::string& e);
// Функция вычисляет выражение в ОПН и возвращает результат
double operator () ();
private:
std::queue<token*> exprQueue;
std::stack<token*> stk;
std::string expr;
void insertDelim();
void fromInfixToPostfix();
bool isDouble(const std::string& rhs);
bool isOperator(const std::string& rhs);
bool isFunction(const std::string& rhs);
bool isConstant(const std::string& rhs);
priority getPriority(const std::string& rhs);
};
};
#endif |
|
calculator.cpp
C++ | 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
| #include "calculator.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <sstream>
#include <regex>
#include <stdexcept>
#include <algorithm>
#include "token.h"
#include "operand.h"
#include "bracket.h"
#include "functions.h"
#include "operators.h"
namespace my
{
calculator::calculator(const std::string& e)
: exprQueue(), stk(), expr(e)
{
fromInfixToPostfix();
}
double calculator::operator () ()
{
while(!exprQueue.empty())
{
token* tok = exprQueue.front();
exprQueue.pop();
if(tok->type() == t_operand)
stk.push(tok);
else if(tok->type() == t_operator)
{
(dynamic_cast<operators*>(tok))->operator()(stk);
delete tok;
}
else if(tok->type() == t_function)
{
(dynamic_cast<functions*>(tok))->operator()(stk);
delete tok;
}
else
throw(std::runtime_error("Illegal bracket construction"));
}
if(stk.size() != 1)
throw(std::runtime_error("Syntax error"));
token* tok = stk.top();
stk.pop();
double result = dynamic_cast<operand*>(tok)->value();
return result;
}
void calculator::insertDelim()
{
const std::string tokensToDelim("^+/*()!,");
size_t index = 0;
while((index = expr.find_first_of(tokensToDelim, index)) != std::string::npos)
{
if((index != 0) && (expr[index - 1] != ' '))
{
expr.insert(index, 1, ' ');
++index;
}
if((index != expr.size() - 1) && (expr[index + 1] != ' '))
expr.insert(++index, 1, ' ');
++index;
}
index = 0;
while((index = expr.find('-', index)) != std::string::npos)
{
bool isUnaryMinus = true;
int n = index - 1;
while(n > 0)
{
if((expr[n] == '(') || (expr[n] == ','))
break;
else if((isdigit(expr[n])) || (expr[n] == ')'))
{
isUnaryMinus = false;
break;
}
else if(isspace(expr[n]))
--n;
else
throw(std::runtime_error("Illegal operators sequence"));
}
if((index != 0) && (expr[index - 1] != ' '))
{
expr.insert(index, 1, ' ');
++index;
}
if((index != expr.size() - 1) && (expr[index + 1] != ' ') && (!isUnaryMinus))
expr.insert(++index, 1, ' ');
++index;
}
}
void calculator::fromInfixToPostfix()
{
insertDelim();
std::istringstream iss(expr);
std::stack<token*> temp;
std::string stok;
while(iss >> stok)
{
for(std::string::iterator it = stok.begin(); it != stok.end(); ++it)
*it = tolower(*it);
if(isDouble(stok))
exprQueue.push(new operand(std::stod(stok)));
else if(isConstant(stok))
{
if(stok == "pi")
exprQueue.push(new operand(M_PI));
else if(stok == "e")
exprQueue.push(new operand(M_E));
}
else if(stok == "(")
temp.push(new bracket(left_bracket));
else if(stok == ")")
{
if(temp.empty())
throw(std::runtime_error("Illegal bracket construction"));
while(temp.top()->type() != t_bracket)
{
exprQueue.push(temp.top());
temp.pop();
if(temp.empty())
throw(std::runtime_error("Illegal bracket construction"));
}
bracket* br = dynamic_cast<bracket*>(temp.top());
temp.pop();
delete br;
if(!temp.empty())
if(temp.top()->type() == t_function)
{
exprQueue.push(temp.top());
temp.pop();
}
}
else if(isOperator(stok))
{
priority pr = getPriority(stok);
while((!temp.empty()) &&
(temp.top()->type() != t_bracket) &&
(pr <= dynamic_cast<operators*>(temp.top())->prior()))
{
exprQueue.push(temp.top());
temp.pop();
}
if(stok == "+")
temp.push(new plus);
else if(stok == "*")
temp.push(new mult);
else if(stok == "/")
temp.push(new divide);
else if(stok == "-")
temp.push(new minus);
else if(stok == "^")
temp.push(new power);
else if(stok == ",")
temp.push(new comma);
else
temp.push(new factorial);
}
else if(isFunction(stok))
{
if(stok == "max")
temp.push(new my::max);
else if(stok == "min")
temp.push(new my::min);
else if(stok == "sin")
temp.push(new my::sin);
else if(stok == "cos")
temp.push(new my::cos);
else if(stok == "asin")
temp.push(new my::asin);
else if(stok == "acos")
temp.push(new my::acos);
else if(stok == "tan")
temp.push(new my::tan);
else if(stok == "atan")
temp.push(new my::atan);
else if(stok == "exp")
temp.push(new my::exp);
else if(stok == "ln")
temp.push(new my::ln);
else if(stok == "lg")
temp.push(new my::lg);
else if(stok == "log")
temp.push(new my::log);
else if(stok == "abs")
temp.push(new my::abs);
else if(stok == "rad")
temp.push(new my::rad);
else if(stok == "degr")
temp.push(new my::degr);
else
temp.push(new my::sqrt);
}
else
throw(std::runtime_error("Illegal token \'" + stok + "\'"));
}
while(!temp.empty())
{
if(temp.top()->type() != t_operator)
throw(std::runtime_error("Illegal bracket construction"));
exprQueue.push(temp.top());
temp.pop();
}
}
bool calculator::isDouble(const std::string& rhs)
{
std::regex re("^-?(?:[1-9]+\\d*|0)(?:\\.\\d+)?$");
return std::regex_match(rhs, re);
}
bool calculator::isOperator(const std::string& rhs)
{
std::string operatorsTable[] =
{
"+", "-", "*", "!", "/", "^", ","
};
size_t size = sizeof operatorsTable / sizeof *operatorsTable;
return (std::find(operatorsTable, operatorsTable + size, rhs) != operatorsTable + size);
}
bool calculator::isFunction(const std::string& rhs)
{
std::string functionsTable[] =
{
"max", "min", "sin", "cos", "asin", "acos",
"tan", "atan", "exp", "log", "lg", "ln",
"abs", "rad", "degr", "sqrt"
};
size_t size = sizeof functionsTable / sizeof *functionsTable;
return (std::find(functionsTable, functionsTable + size, rhs) != functionsTable + size);
}
bool calculator::isConstant(const std::string& rhs)
{
std::string constantsTable[] =
{
"pi", "e"
};
size_t size = sizeof constantsTable / sizeof *constantsTable;
return (std::find(constantsTable, constantsTable + size, rhs) != constantsTable + size);
}
priority calculator::getPriority(const std::string& rhs)
{
if(rhs == ",")
return pr0;
if((rhs == "+") || (rhs == "-"))
return pr1;
if((rhs == "*") || (rhs == "/"))
return pr2;
if(rhs == "^")
return pr3;
else
return pr4;
}
}; |
|
main.cpp
C++ | 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
| #include <iostream>
#include <regex>
#include "calculator.h"
int main()
{
try
{
std::string str;
while(true)
{
std::cout << "Input an expression to calculate (Ctrl+Z to exit):" << std::endl;
if(!std::getline(std::cin, str))
break;
if(str.empty())
continue;
my::calculator calc(str);
std::cout << "Result = " << calc() << std::endl << std::endl;
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
system("pause");
return EXIT_SUCCESS;
} |
|
7
|