易错点

  1. double类型很容易误写成int类型
  2. if else要穷尽所有情况

tips

  1. 一个从字符串中提取数字的函数:nextnum
  2. cctype中的isdigit(char)
  3. 将栈传递给函数的时候相当于一个变量,而不是一个地址

代码

#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
#include <cctype>
using namespace std;

//简单计算器
int prior(char c){
    if(c=='#')return 0;
    if(c=='$')return 1;
    if(c=='+'||c=='-')return 2;
    if(c=='*'||c=='/')return 3;
    else return 4;
}
double nextnum(string str,int i){
    int ans=0;
    while(isdigit(str[i])){
        ans=ans*10+str[i]-'0';
        i++;
    }
    return ans;
}
double calc(double x,double y,char flag){
    if(flag=='+')return(x+y);
    else if(flag=='-')return(x-y);
    else if(flag=='*')return(x*y);
    else if(flag=='/')return(x/y);
    else return 0;
}

int main(){
    string input;
    while(1){
        stack<char>fuhao;
        fuhao.push('#');
        stack<double>shuzi;
        getline(cin,input);
        if(input=="0")break;
        input=input+'$';
        int i=0;
        while(fuhao.top()!='$'){
            if(input[i]==' '){
                i++;
                continue;
            }
            else if(isdigit(input[i])){
                double nextn=nextnum(input,i);
                shuzi.push(nextn);
                while(isdigit(input[i]))i++;
            }
            else{
                char flag=input[i];
                char flag_in_stack=fuhao.top();
                if (prior(flag)>prior(flag_in_stack)){
                    fuhao.push(flag);
                    i++;
                }
                else{
                    fuhao.pop();
                    double y=shuzi.top();
                    shuzi.pop();
                    double x=shuzi.top();
                    shuzi.pop();
                    double ans=calc(x,y,flag_in_stack);
                    shuzi.push(ans);
                }
            }
        }
        printf("%.2f\n",shuzi.top());
        }
    return 0;
}