任意输入一个简单的进行加减乘除运算的表达式,能够输出表达式的值.
如输入:2*3+4/2 输出:8 表达式是任意给顶合法的表达式 (利用栈来完成)
/////////////////////////////////////////////////////////////
// File Name : calculator.cpp
/////////////////////////////////////////////////////////////
#include <iostream>
#include <stack>
#include <list>
#include <cmath>
#define NDEBUG
using namespace std;
double toi(char*, int*);
int test(char);
stack<double, list<double> > num;
stack<char, list<char> > op;
int main()
{
op.push('\0');
char exp[100];
cin.getline(exp, 100, '\n');
int n = 0;
int len;
len = strlen(exp);
#ifndef NDEBUG
cout << exp << endl;
#endif
while (exp[n] != '\0')
{
if (exp[n] == ' ')
{
for (int nn = n + 1;nn < len; nn++)
exp[nn-1] = exp[nn];
len--;
n--;
}
n++;
}
exp[len] = '\0';
#ifndef NDEBUG
cout << exp;
#endif
int k;
k = 0;
int flag = 1;
char c;
c = exp[0];
while (flag)
{
if (c >= '0' && c <= '9' || c == '.')
num.push(toi(exp, &k));
else if (c == '(' || test(c) > test(op.top()))
{
op.push(c);
k++;
}
else if (c == '\0' && op.top() == '\0')
flag = 0;
else if (c == ')' && op.top() == '(')
{
op.pop();
k++;
}
else if (test(c) <= test(op.top()))
{
double y = num.top();
num.pop();
double x = num.top();
num.pop();
c = op.top();
op.pop();
switch (c)
{
case '*': x *= y; break;
case '/': x /= y; break;
case '+': x += y; break;
case '-': x -= y; break;
case '^': x = pow(x, y); break;
default : cout << "Error!!\n"; break;
}
num.push(x);
}
c = exp[k];
}
cout << endl << exp << " = " << num.top() << endl << endl;
system("pause");
return 0;
}
double toi(char* c, int* k)
{
double x, y = 1.0;
int flag = 1;
char s;
x = 0.0;
s = c[*k];
while (s >= '0' && s <= '9' || s == '.')
{
*k = *k + 1;
if (s >= '0' && s <= '9')
if (flag == 1)
x = 10*x + (s - 48);
else
{
y *= 0.1;
x += y * (s - 48);
}
else
flag = 0;
s = c[*k];
}
return (x);
}
int test(char c)
{
int x;
switch (c)
{
case '^' : x = 3; break;
case '*' : x = 2; break;
case '/' : x = 2; break;
case '+' : x = 1; break;
case '-' : x = 1; break;
case '(' : x = 0; break;
case ')' : x = 0; break;
case '\0' : x = -1; break;
}
return (x);
}