sicily 后缀表达式计算

来源:互联网 发布:vivox9l破解网络锁 编辑:程序博客网 时间:2024/05/19 15:39

WA了无数次心都碎了,一直改到3点多才交上的= =感觉思想很简单,使用了一个栈。依次遍历字符串,若为字幕的话,则将其push到栈中,若为运算符号,则将栈顶元素与下一个元素进行运算,然后将运算的结果push进去栈中。。依次执行这些操作即可。

代码如下:

#include<iostream>#include<iomanip>#include<string>#include<stack>using namespace std;int main() {    int n;    string s;    cin>>n;    while (n--) {           cin>>s;        stack<double>table;        double num = 0, temp, temp1;        for (int i = 0 ; i < s.size() ; i++) {            if (s[i]>=97 && s[i]<=122)                table.push(s[i]-96); // 根据asc码来的            else {                temp = table.top();  // 将栈顶元素设为temp,并将其pop掉,然后计算temp和当前的栈顶元素                table.pop();                temp1 = table.top();                table.pop();                if (s[i] ==43) {                    num = temp + temp1;                    table.push(num);                }                else if (s[i] ==45) {                    num = temp1 - temp;                    table.push(num);                }                 else if (s[i] == 42) {                    num =  temp * temp1;                    table.push(num);                }                else if (s[i] ==47) {                    num = temp1 / temp;                    table.push(num);                }            }        }        cout <<fixed <<setprecision(2) <<num <<endl; // C++保留两位小数的方法,记得头文件要写#include<iomanip>    }    return 0;}                                 


0 0
原创粉丝点击