我的思路是先中缀变后缀,然后计算后缀表达式。
#include <iostream>
#include <stack>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int priority(char op)
{
switch (op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
}
int opToInt(char op)
{
switch (op)
{
case '+': return -1;
case '-': return -2;
case '*': return -3;
case '/': return -4;
default:
break;
}
}
int main()
{
char s[201];
stack<double> on;
stack<char> op;
stack<double> on2;
double temp;
char temp_num[201];
int l, i;
int ll, j;
int k;
while (1)
{
memset(s, 0, 201);
//
scanf("%[^\n]", s);
//
if (strlen(s) == 1 && s[0] == '0') return 0;
l = strlen(s);
memset(temp_num, 0, 201);
for (i = 0; i < l; i++)
{
if (s[i] == ' ' && s[i - 1] >= '0'&&s[i - 1] <= '9')
{
ll = strlen(temp_num);
temp = 0;
k = 0;
for (j = ll - 1; j >= 0; j--)
{
temp = (temp_num[j] - '0') * pow(10, k++) + temp;
}
on.push(temp);
memset(temp_num, 0, 201);
}
else if (s[i] == ' ')
{
}
else if (s[i] >= '0'&&s[i] <= '9')
{
ll = strlen(temp_num);
temp_num[ll] = s[i];
}
else // op
{
if (op.empty()) { op.push(s[i]); }
else
{
while(!op.empty() && priority(op.top()) >= priority(s[i]))
{
on.push(opToInt(op.top()));
op.pop();
}
op.push(s[i]);
}
}
}
ll = strlen(temp_num);
temp = 0;
k = 0;
for (j = ll - 1; j >= 0; j--)
{
temp = (temp_num[j] - '0') * pow(10, k++) + temp;
}
on.push(temp);
while (!op.empty())
{
on.push(opToInt(op.top()));
op.pop();
}
while (!on.empty())
{
on2.push(on.top());
on.pop();
}
while (!on2.empty())
{
if (on2.top() < 0)
{
int op = on2.top();
on2.pop();
double right = on.top();
on.pop();
double left = on.top();
on.pop();
double res;
switch (op)
{
case -1:res = left + right; break;
case -2:res = left - right; break;
case -3:res = left * right; break;
case -4:res = left / right; break;
}
on.push(res);
}
else
{
on.push(on2.top());
on2.pop();
}
}
printf("%.2lf\n", on.top());
//cout << on.top() << endl;
getchar();
on.pop();
}
}
更简单的方法:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<double> t;
int sign;
double num;
double temp;
char c;
double sum;
while (1)
{
scanf("%lf", &num);
sign = 1;
t.push(num);
while ('\n' != getchar())
{
sign = 0;
scanf("%c %lf", &c, &num);
if ('+' == c)
t.push(num);
else if ('-' == c)
t.push(-num);
else if ('*' == c)
{
temp = t.top();
temp *= num;
t.pop();
t.push(temp);
}
else if ('/' == c)
{
temp = t.top();
temp /= num;
t.pop();
t.push(temp);
}
}
if (1 == sign) // '0\n'
break;
sum = 0;
while (!t.empty())
{
sum += t.top();
t.pop();
}
printf("%.2lf\n", sum);
}
return 0;
}