读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
利用栈,一个存放数字,一个存放+-运算符。
要注意的问题是
1、数字不一定是个位数,所以要用进制的知识来转化数字。
2、区分优先级,先算乘除 后算加减 ,所以如果遇到乘除运算符,将数字栈顶出栈,和 i + 2 位置的数字进行运算。如果遇到加减,若运算符栈空,则入栈,否则,将数字栈顶元素与运算符的下一个数字进行运算
可以用这个式子模拟一下
55 + 22 * 3 / 11 - 5
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <cstdio>
using namespace std;
int main()
{
stack<char>op;
stack<double>number;
string s;
double operand1,operand2;
while(getline(cin,s)){
if(s=="0")
break;
for(int i=0;s[i];i++){
if(isdigit(s[i])){ //是数字
operand1=0;
while(isdigit(s[i])){ //如果不是个位数
operand1=operand1*10+s[i]-'0';
i++;
}
i--;
number.push(operand1); //入栈
}
else if(s[i]=='+'||s[i]=='-'){ //是加号或减号
if(op.empty()){ //栈空,入栈
op.push(s[i]);
}
else{ //栈不空,先运算再入栈
char sop=op.top();
op.pop();
operand1=number.top();
number.pop();
operand2=number.top();
number.pop();
if(sop=='+')
number.push(operand1+operand2);
else
number.push(operand2-operand1);
op.push(s[i]);
}
}
else if(s[i]=='*'||s[i]=='/'){ //是乘除
op.push(s[i]); //利用栈先存下s[i],这样就不用分配多余的存储空间了
i+=2; //运算符与数字之间隔着一个空格,所以运算符加2必然是数
operand2=0;
while(isdigit(s[i])){
operand2=operand2*10+s[i]-'0';
i++;
}
i--;
operand1=number.top();
number.pop();
if(op.top()=='*')
number.push(operand1*operand2);
else
number.push(operand1/operand2);
op.pop(); //暂时存储的运算符出栈
}
}
while(!op.empty()){ //栈内还有未参与运算的加减号
char sop=op.top();
op.pop();
operand1=number.top();
number.pop();
operand2=number.top();
number.pop();
if(sop=='+')
number.push(operand1+operand2);
else
number.push(operand2-operand1);
}
printf("%.2f\n",number.top());
}
return 0;
}
3、