Fork me on GitHub

C++实现简单计算器


利用编译原理中递归下降的 语法分析语义分析 ,使用 C++ 实现简单计算器。

文法如下:
EXP -> TERM {AlphaOP TERM}
TERM -> FACTOR {BetaOP FACTOR}
FACTOR -> (EXP) | number
AlphaOP -> + | -
BetaOP -> * | \


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
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

/*
* EXP -> TERM {AlphaOP TERM}
* TERM -> FACTOR {BetaOP FACTOR}
* FACTOR -> (EXP) | number
* AlphaOP -> + | -
* BetaOP -> * | \
*/

string inputExp;
string::iterator ite;

void handleError();
void matchChar(char token);
double matchDigit();
double factor();
double term();
double expression();

//错误处理
void handleError() {
cerr << "Error expression ! " + inputExp <<endl;
exit(-1);
}

//匹配字符
void matchChar(char token) {
if (*ite == token) {
ite++;
}
else {
handleError();
}
}

//匹配数字
double matchDigit() {
string tempString = "";
while (isdigit(*ite)) {
tempString += *ite;
ite++;
}
istringstream iss(tempString);
double temp;
iss >> temp;
return temp;
}

double factor() {
double temp;
if (isdigit(*ite)) {
temp = matchDigit();
}
else if (*ite == '(') {
matchChar('(');
//处理负数
if(*ite == '-'){
ite++;
temp = matchDigit() * (-1);
}
else{
temp = expression();
}
matchChar(')');
}
else {
handleError();
}

return temp;
}

double term() {
double temp = factor();
while (*ite == '*' || *ite == '/') {
if (*ite == '*') {
matchChar('*');
temp = temp * factor();
}
else {
matchChar('/');
temp = temp / factor();
}
}
return temp;
}

double expression() {
double temp = term();
while (*ite == '+' || *ite == '-') {
if (*ite == '+') {
matchChar('+');
temp = temp + factor();
}
else {
matchChar('-');
temp = temp - factor();
}
}
return temp;
}

int main() {
double result = 0;
cout << "请输入表达式:";
cin >> inputExp;

//加上空格防止迭代器溢出
inputExp += " ";
ite = inputExp.begin();

while (*ite != inputExp.back()) {
result = expression();
}

cout << result << endl;

system("pause");
return 0;
}
扫描二维码,拯救贫困山区大学生!
-------------本文结束感谢您的阅读-------------