c++表达式计算

c++
a=str.find_first_of(op,1); //表示从str字符串的1位置开始查找op字符串;
若找到:a==string::npos;
否则:a!=string::npos;

计算表达式

#include "iostream"
#include "cstdio"
#include "string"
#include "stack"
#include "vector"
#include "stdlib.h"
using namespace std;

int judge(char c1, char c2) {              //比较栈顶和输入字符比较级
    int a1, a2;
    if('+' == c1 || '-' == c1)               //栈顶c1,输入c2
        a1 = 3;
    if('*' == c1 || '/' == c1)
        a1 = 5;
    if('(' == c1)
        a1 = 1;
    if(')' == c1)
        a1 = 7;
    if('#' == c1)
        a1 = 0;



    if('+' == c2 || '-' == c2)
        a2 = 2;
    if('*' == c2 || '/' == c2)
        a2 = 4;
    if('(' == c2)
        a2 = 6;
    if(')' == c2)
        a2 = 1;
    if('#'==c2)
        a2=0;


    if(a1 > a2)
        return 1;
    if(a1 < a2)
        return -1;
    if(a1 == a2)
        return 0;

}

double run(char c, double d1, double d2) {      //四则运算
    switch (c) {
    case '+':
        return d1 + d2;
        break;
    case '-':
        return d1 - d2;
        break;
    case'*':
        return d1 * d2;
        break;
    case '/':
        return d1 / d2;
        break;
    default:
        return 0.0;
        break;
    }
}

double cal(string str) {
    const char * op ="+-*/()#";            //比较的算术符号
    str.append(1,'#');            //附加#以便比较
    stack<char> optr;              //算术符栈
    stack<double> optd;                  //数字栈

    int a=-1;
    optr.push('#'); //入栈
    while(true){
        int b=a+1;
        a=str.find_first_of(op,a+1); //从a+1处查找运算符
        if(a == string::npos) break;    //未找到
        if(a!=b){
            string ss(str,b,a-b);                      //定义子串
            double d=atof(ss.c_str());					//转化
            optd.push(d);
        }

        int ju =judge(optr.top(),str[a]);
        if(-1==ju){
            optr.push(str[a]);
        }
        if(0==ju){
            optr.pop();
        }
        if(1==ju){                                  //出栈计算再将结果入栈
            double d1=optd.top();
            optd.pop();
            double d2=optd.top();
            optd.pop();
            d1=run(optr.top(),d2,d1);

            optd.push(d1);
            optr.pop();
            a--;
        }
    }
    str.erase(str.length()-1,1);                        //消除字符
    return optd.top();

}
int main() {
      int n;
      cin >> n;
      const int m=n;
      vector<double> display(n+1);
      while(n>0){
        string str;
        cin>>str;
        double result=cal(str);
        display[n]=result;
        n--;
      };
      for(int j=m;j>0;j--){
        printf("%.1f\n",display[j]);
        }
        system("pause");
        return 0;


}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值