c++ 手写计算器

数据结构课上老师布置了个作业,让自己写一个计算器,要求支持小数运算及括号,早上刷牙时构思了一下,发现可以用两个栈来实现。

其中,一个栈用来存运算符,一个栈用来存运算的数,利用栈将输入的中缀表达式转化为计算机容易处理的后缀表达式,当存运算符的栈中pop出运算符时,就取存运算数的栈上的前两个进行运算,在将运算结果压入栈中。

具体实现代码如下

#include<iostream>
#include<cstring>
#include<stack>
using namespace std;

stack<double> num;
stack<char> sign;

void calc(char c){
    double a,b;
    a=num.top();
    num.pop();
    b=num.top();
    num.pop();
    if(c=='+')
        num.push(a+b);
    else if(c=='-')
        num.push(b-a);
    else if(c=='*')
        num.push(a*b);
    if(c=='/')
        num.push(b/a);
}

double solve(string s){

    char top;
    double ans=0;
    char c;
    double n=0;
    int len=s.length();
    double m=1,d=0;
    for(int i=0;i<len;i++){
        c=s[i]; 
        if(c>=48&&c<=57){
            if(d==0.0){
                n=n*m+int(c-48);
                m*=10;
            }
            else{
                n=n+d*int(c-48);
                d*=0.1;
            }
        }
        else if(c=='.'){
            d=0.1;
        }
        else if(c=='+'||c=='-'){
            if(s[i-1]!=')')
                num.push(n);
            n=0;
            m=1;
            d=0;
            if(!sign.empty()){
                top=sign.top();
                while((top=='*'||top=='/'||(top=='-'&&c=='-'))&&!sign.empty()){
                    calc(top);
                    sign.pop();
                    if(!sign.empty())
                        top=sign.top();
                }
            }
            sign.push(c);
        }
        else  if(c=='*'||c=='/'){
            if(s[i-1]!=')')
                num.push(n);
            n=0;
            m=1;
            d=0;
            if(!sign.empty()){
                top=sign.top();
                while((top=='/'&&c=='/')&&!sign.empty()){
                    calc(top);
                    sign.pop();
                    if(!sign.empty())
                        top=sign.top();
                }
            }
            sign.push(c);
        }
        else if(c=='('){
            sign.push(c);
        }
        else if(c==')'){
            num.push(n);
            if(!sign.empty())
                top=sign.top();
            while(top!='('){
                calc(top);
                sign.pop();
                top=sign.top();
            }
            sign.pop();
        }
        else{
            printf("Error! Illgal input!EXIT_");
            return 0;
        }
    }
    if(s[len-1]!=')')
        num.push(n);
    while(!sign.empty()){
        top=sign.top();
        calc(top);
        sign.pop();
    };
    ans=num.top();
    return ans;
}

int main(){
    cout<<"Please input what u want to calculate:";
    string s;
    cin>>s;
    //s="(5.3-9)*2.6/1.3+4";
    cout<<solve(s);
    return 0;
}

基本可以实现简单的运算

 

 经验证结果正确

猜你喜欢

转载自www.cnblogs.com/r3t7rn/p/11717492.html
今日推荐