- 这个利用堆栈做成的简易计算器,但是只能支持不带小数的计算,刚刚想了一会没钻研出来小数的计算,等我钻研出来了继续更新。
- 需要提前掌握堆栈 中缀表达式转后缀表达式的知识点。
- 水平有限,请多多指教相互学习嘻嘻。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
double number(string& s, int&i){
int m = 0;
int j;
int k = 0;
int a[10] = { 0 };
for (j = i; s[j] < '10' && s[j]>'0'; j++) {
a[m] = s[j] - '0';
m++;
}
i = j - 1;
for (j = 0; j < m; j++)
k += a[j] * pow(10, m - j-1);
return k;
}
int Rank(char ch) {
if (ch == '+' || ch == '-')
return 1;
if (ch == '*' || ch == '/')
return 2;
if (ch == '(')
return 0;
}
string transform(string& s) {
int i = 0; int j = 0;
stack<char>c;
char ch[100];
for (i = 0; i < s.size(); i++) {
if (s[i] == ' ')
continue;
if (s[i] < '10' && s[i]>'0') {
while (s[i] < '10' && s[i]>'0') {
ch[j] = s[i];
i++;
j++;
}
ch[j] = ' ';
j++;
i--;
}
else {
if (c.empty())
c.push(s[i]);
else if (s[i] == ')') {
while (c.top() != '(') {
ch[j] = c.top();
j++;
c.pop();
}
c.pop();
}
else if (s[i] == '(') {
c.push(s[i]);
}
else if (Rank(s[i]) > Rank(c.top())) {
c.push(s[i]);
}
else
{
while (!c.empty() && (Rank(s[i]) <= Rank(c.top()))) {
ch[j] = c.top();
j++;
c.pop();
}
c.push(s[i]);
}
}
}
while (!c.empty()) {
ch[j] = c.top();
j++;
c.pop();
}
string s1(ch, 0, j);
return s1;
}
double caculate(string& s) {
int i, k;
double a, b;
stack<double>v;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ')
continue;
else if (s[i] < '10' && s[i]>'0')
v.push(number(s, i));
else {
a = v.top(), v.pop();
b = v.top(), v.pop();
switch (s[i]) {
case'+':v.push(a + b); break;
case'-':v.push(b-a); break;
case'*':v.push(a * b); break;
case'/':v.push(b/a); break;
}
}
}
return v.top();
}
int main()
{
string s1, s2;
getline(cin, s1);
s2 = transform(s1);
double result = caculate(s2);
cout << result << endl;
return 0;
}