计算器程序,可以计算正实数范围内的任何数据的加减乘除括号,混合运算

//计算器程序
//可以计算正实数的四则混合运算
//完成于07年6月3日 17:06
#include<iostream>
#include<sstream>
#include<string>
#include<iterator>
#include<algorithm>
#include<stack>
using namespace std;
const string operstr("+-*/()#");
                //      +  -  *  /  (  )  #
int gradation[7][7]={ 1, 1,-1,-1,-1, 1, 1,    //0: +
                      1, 1,-1,-1,-1, 1, 1,    //1: -
                      1, 1, 1, 1,-1, 1, 1,    //2: *
                      1, 1, 1, 1,-1, 1, 1,    //3: /
                     -1,-1,-1,-1,-1, 0, 3,  //4: (
                      1, 1, 1, 1, 3, 1, 1,    //5: )
                     -1,-1,-1,-1,-1, 3, 0    //6: #
};
int Precede(char a, char b)
{
    int posa=find(operstr.begin(), operstr.end(), a) - operstr.begin();
    int posb=find(operstr.begin(), operstr.end(), b) - operstr.begin();
    return gradation[posa][posb];
}
double counte(double a,char o,double b)
{
    switch(o)
    {
    case '+':
        return a+b;
        break;
    case '-':
        return a-b;
        break;
    case '*':
        return a*b;
        break;
    case '/':
        return a/b;
        break;
    }
    return 0;
}
void main()
{
    cout<<"请输入表达式:";
    string s;
    cin>>s;
    s+='#';

    istringstream iss(s);    
    istream_iterator<char> input(iss);
    istream_iterator<char> end_input;

    stack<char> operate;            //操作符栈    
    stack<double> operand;            //操作数栈
    operate.push('#');

    while((input!=end_input&&*input!='#')||operate.top()!='#')
    {
        if(operstr.end()!=find(operstr.begin(),operstr.end(),*input))
        {
            //operate.push(*input++);                    //操作符进栈
            switch(Precede(operate.top(),*input))
            {
            case -1:                //栈顶元素优先权低
                operate.push(*input++);
                break;
            case 0:                    //脱去括号并接收下一个字符
                operate.pop();
                input++;
                break;
            case 1:                    //退栈并将运算结果入栈
                char o=operate.top();
                operate.pop();
                double b=operand.top();
                operand.pop();
                double a=operand.top();
                operand.pop();

                operand.push(counte(a,o,b));
                break;
            }
        }
        else
        {                                                    
            string Snum;
            double Dnum=0;
            for(;operstr.end()==find(operstr.begin(),operstr.end(),*input);Snum+=*input++)
                ;                                    //获得伪操作数
            istringstream ISSnum(Snum);
            ISSnum>>Dnum;                            //获得真操作数
            operand.push(Dnum);                        //操作数进栈
        }
    }
    cout<<"计算结果是: ";
    cout<<string(s.begin(),s.end()-1)<<"="<<operand.top()<<endl;//计算结果
}

 

 

上学时候写的。现在发现有人那这个做面试题。

posted @ 2012-09-18 14:58  崇山峻岭  阅读(385)  评论(0编辑  收藏  举报