llllmz

导航

KY129 简单计算器C++

这是目前阶段做的最难最吃力的题目。调试了一遍又一遍去看逻辑上出现的各种问题。。。

#include<iostream>
#include<string>
#include<stack>
#include<map>
using namespace std;

int main(){
    map<char,int> m={
            {'+',0},{'-',0},
            {'*',1},{'/',1},
            {'#',-1}
    };
    string s;
    while(getline(cin,s)){
        s.push_back('#');
        if(s=="0") break;
        stack<float> f;
        stack<char> c;
        int i=0;
        while(i<s.size()){
            string a;
            for(;i<s.size();i++){
                if(s[i]<='9'&&s[i]>='0'){
                    a.push_back(s[i]);
                }else{
                    break;
                }
            }
            if(a.size()!=0) f.push(stof(a));
            if(s[i]==' ') {
                i++;
            }else{
                if(c.size()==0){
                    c.push(s[i]);
                    i++;
                }else{
                    if(m[s[i]]<=m[c.top()]){
                        float b=f.top();
                        f.pop();
                        float  a=f.top();
                        f.pop();
                        char x=c.top();
                        c.pop();
                        if(x=='+'){
                            a=a+b;
                        }else if(x=='-'){
                            a=a-b;
                        }else if(x=='*'){
                            a=a*b;
                        }else{
                            a=a/b;
                        }
                        f.push(a);
                    }else{
                        c.push(s[i]);
                        i++;
                    }
                }
            }
        }
        if(c.size()!=0 &&c.top()=='#') {
            printf("%.2f", f.top());
            break;
        }
    }
    return 0;
}

结果如下:

posted on 2024-01-18 22:15  神奇的萝卜丝  阅读(38)  评论(0)    收藏  举报