备战快速复习--day1

逗号运算符,只保留第一个运算符的结果。

var=(3*4,4*5,5*6)结果是12 

while(cin>>a,a!=EOF)这个是读取a,后半句是判断条件。在书上看到的两个用法,不是特别常见。

getline函数:普通cin只能读取非空格,这个可以读带空格的,读一行

getline(cin,str)

#include<queue>
#include<string.h>
#include<string>
#include<iostream>
#include<stack>
#include<map>
#include<stdio.h>
using namespace std;
struct node
{
    double num;
    char op;
    bool flag;//true代表操作数,false代表操作符
};
string str;//用于存储输入串
stack<node> s;//操作符栈
queue<node> q;//后缀表达式队列
map<char,int> op;//用于映射优先级。
void Change(){
    double num;//用于存储当前操作数
    node temp;//用于存储当前点,辅助入栈
    for(int i=0;i<str.length();)
    {
        if(str[i]>='0' && str[i]<='9')
        {
            temp.flag=true;
            temp.num=str[i++]-'0';
            while(i<str.length() && str[i]>='0' && str[i]<='9')
            {
                temp.num=temp.num*10+str[i]-'0';
                i++;
            }
            q.push(temp);
        }
        else
        {
            temp.flag=false;
            while(!s.empty() && op[str[i]]<=op[s.top().op])
            {
                q.push(s.top());
                s.pop();
            }//如果目前操作栈顶端由字符且他的优先级大于等于目前字符首部的str,栈顶持续移入后缀表达式对应队列。
            temp.op=str[i];
            s.push(temp);//操作符都先转成node以后存在操作符栈里面呆着
            i++;
        }
    }
    while(!s.empty())
    {
        q.push(s.top());
        s.pop();
    }
}
double Cal()
{
    double temp1,temp2;
    node cur,temp;
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        if(cur.flag==true)//数直接压栈,操作符的话,从栈中取两个操作符然后算出结果并压栈。
            s.push(cur);
        else
        {
            temp2=s.top().num;
            s.pop();
            temp1=s.top().num;//前面操作数被压入栈的顺序和实际是相反的
            s.pop();
            temp.flag=true;
            if(cur.op=='+')
                temp.num=temp1+temp2;//注意一下temp1和temp2都是数字,temp用于压栈是完整的node
            else if(cur.op=='-')
                temp.num=temp1-temp2;
            else if(cur.op=='*')
                temp.num=temp1*temp2;
            else
                temp.num=temp1/temp2;
            s.push(temp);
        }
    }
    return s.top().num;//最后的结果在栈里,也是栈中唯一的数字。
}
int main()
{
    op['+']=op['-']=1;
    op['*']=op['/']=2;
    while(getline(cin,str), str!="0")
    {
        for(string::iterator it=str.end();it!=str.begin();it--)
        {
            if(*it==' ') str.erase(it);
        }
        while(!s.empty()) s.pop();
        Change();
        printf("%.2f
",Cal());
    }
    return 0;
}
中缀转后缀标程计算

 因为不仅一行输入数据,在下一轮进来的时候清空上一轮的s(q在上一轮结束会被清空,s里面一定会有一个元素的)

还有就是在计算后缀表达式,计算结果后操作数压入栈里面的时候因为第二轮都是数,所以标记不标记flag是数字都行的。

时间才能证明一切,选好了就尽力去做吧!
原文地址:https://www.cnblogs.com/tingxilin/p/12312070.html