计算器模拟
题目
1.中缀转为后缀
2.题目考察逆波兰表达式
注意事项:
增加括号用法
atoi_将string转为int: atoi(str.c_str())
换行
多位数字:往后遍历
stack: 没有clear用法swap ////// 清空的多种方法
string和intchar之间频繁转换是难点
string转int
将多位数字压栈处理
#include <iostream>
#include <stack>
#include <cstring>
#include <iomanip>
using namespace std;
stack<string> s1;
stack<char> s2;
stack<string> s3;
int getL(char a) {
switch (a) {
case '+': {
return 4;
break;
}
case '-': {
return 4;
break;
}
case '*': {
return 5;
break;
}
case '/': {
return 5;
break;
}
default:
break;
}
return 0;
}
void g(char words[], int len) {
stack<string>().swap(s1);
stack<char>().swap(s2);
string ts;
for (int i = 0; i < len; ++i) {
if (words[i] == ' ')
continue;
if (words[i] == '+' || words[i] == '-' || words[i] == '*' || words[i] == '/') {
while (true) {
if (s2.empty() || s2.top() == '(') {
char t = words[i];
s2.push(t);
break;
}
int l = getL(words[i]);
int la = getL(s2.top());
if (l > la) {
char t = words[i];
s2.push(t);
break;
} else {
string t;
t.push_back(s2.top());
s1.push(t);
s2.pop();
}
}
} else if ( words[i] >= '0' && words[i] <= '9') {//难点
string t;
t.push_back(words[i]);
while (words[i + 1] >= '0' && words[i + 1] <= '9' ) {
t.push_back(words[i + 1]);
++i;
}
s1.push(t);
} else {
if (words[i] == '(') {
s2.push(words[i]);
} else {
while (s2.top() != '(') {
string t;
t.push_back(s2.top());
s1.push(t);
s2.pop();
}
s2.pop();
}
}
}
while (!s2.empty()) {
string t;
t.push_back(s2.top());
s1.push(t);
s2.pop();
}
string Re;
while (!s1.empty()) {
Re = s1.top();
s1.pop();
s3.push(Re);
}
}
int isop(string a) {
if (a == "*" || a == "+" || a == "-" || a == "/")
return 1;
else
return 0;
}
int main() {
char words[1000];
int len;
stack<double> ans;
string ch;
while (gets(words)) {
if (words[0] == '0' && strlen(words) == 1)
break;
len = strlen(words);
g(words, len);
int temp = s1.size();
double a, b;
while (!s3.empty()) {
if (isop(s3.top())) {
b = ans.top();
ans.pop();
a = ans.top();
ans.pop();
ch = s3.top();
if (ch == "+") {
a = a * 1.0 + b;
ans.push(a);
} else if (ch == "-") {
a = a * 1.0 - b;
ans.push(a);
} else if (ch == "*") {
a = a * 1.0 * b;
ans.push(a);
} else {
a = a * 1.0 / b;
ans.push(a);
}
s3.pop();
} else {
ch = s3.top();
a = atoi(ch.c_str());
ans.push(a);
s3.pop();
}
}
double outA = ans.top();
cout << setiosflags(ios::fixed) << setprecision(2) << outA << endl;
ans.pop();
}
return 0;
}
722

被折叠的 条评论
为什么被折叠?



