-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevalStr.cpp
More file actions
92 lines (75 loc) · 1.9 KB
/
Copy pathevalStr.cpp
File metadata and controls
92 lines (75 loc) · 1.9 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
//
// Created by Lenovo on 2021/10/9.
//
#include "evalStr.h"
#include <utility>
evalStr::evalStr():pos(-1),ch(' '),Str(" ") {}
evalStr::evalStr(std::string inStr):pos(-1),ch(' '),Str(std::move(inStr)){
}
void evalStr::nexchar() {
ch = (++pos < Str.length())? Str[pos] : -1;
}
bool evalStr::check(int testChar) {
while (ch == ' ') nexchar();
if (testChar == ch)
{
nexchar();
return true;
}
return false;
}
double evalStr::eval() {
nexchar();
double x = Expression();
if (pos < Str.length()) std::cout<<"wrong ch: "<<ch<<std::endl;
;
return x;
}
double evalStr::Expression() {
double x = Term();
for(;;) {
if (check('+')) x += Term();
else if (check('-')) x -= Term();
else return x;
}
}
double evalStr::Term() {
double x = Factor();
for(;;){
if (check('*')) x *= Factor();
else if (check('/')) x /= Factor();
else return x;
}
}
double evalStr::Factor() {
double x;
int startPos = pos;
if (check('+')) return x =Factor();
if (check('-')) return x = -Factor();
if(check('('))
{
x = Expression();
check(')');
}
else if ((ch >= '0' && ch <= '9') || ch == '.')
{
while ((ch >= '0' && ch <= '9') || ch == '.') nexchar();
std::string subStr(&Str[startPos],&Str[pos]);
x = std::stoi(subStr);
}
else if (ch >= 'a' && ch <= 'z')
{
while (ch >= 'a' && ch <= 'z') nexchar();
std::string subStr(&Str[startPos],&Str[pos]);
x = Factor();
if (subStr == "sin") x = sin(x);
else if (subStr == "cos") x = cos(x);
else if (subStr == "tan") x = tan(x);
else if (subStr == "sqrt") x = sqrt(x);
else std::cout<<"wrong function"<<std::endl;
}
else
std::cout<<"wrong ch"<<std::endl;
if (check('^')) x = pow(x,Factor());
return x;
}