计算表达式——运算问题

文章详细描述了如何利用两个栈(一个存储数字,一个存储运算符)和优先级规则,解决无括号的表达式计算问题。通过定义islevel函数判断运算符级别,确保正确的计算顺序。
摘要由CSDN通过智能技术生成

描述

对于一个不存在括号的表达式进行计算

输入描述:

存在多组数据,每组数据一行,表达式不存在空格

输出描述:

输出结果

示例1

输入:

6/2+3+3*4

输出:

18

解题思路:

(1)定义两个栈,分别存放数字和运算符;

(2)设置运算符等级函数,那个等级高,先优先计算;

(3)设置结束字符;

代码:

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

int islevel(char c){  //判断字段等级函数
    int level;
    if(c=='#'){
         level=1;
    }else if (c=='&') { //结束字符
        level=2;
    }else if (c=='+'||c=='-') {
        level= 3;
    }else if(c=='*'||c=='/'){  //最高级为乘和除
        level= 4;
    }
    return level;
}

double calculate(double a,double b,char c){  //计算函数
    double result;
    if(c=='-'){
        result= a-b;
    }else if (c=='+') {
        result= a+b;
    }else if (c=='*') {
        result= a*b;
    }else if (c=='/') {
        result= a/b;
    }
    return result;
}

int main() {
    stack<double> num;  //数字栈
    stack<char> sc;  //字符栈

    string str;
    while (getline(cin,str)) {
        str +='&';//结束字符;
        int index=0;//字符串的位置指针;
        sc.push('#');  //压入栈底字符标志

        while(index<str.length()) {
            if(isdigit(str[index])){//该位置为数字
                double number=0;
                while (isdigit(str[index])) {  //判断是否有大于10整数
                    number=number*10+str[index]-'0';
                    index++;
                }
                num.push(number);  //压入数字栈

            }else{  //该位置为字符
                char c=str[index];
                if(islevel(sc.top()) < islevel(c) ){  //字符栈中的等级比现在遍历的小
                    sc.push(c);//压入字符
                    index++;
                }else{
                    double num1=num.top();
                    num.pop(); //删除数字
                    double num2=num.top();
                    num.pop();
                    double sum=calculate(num2,num1,sc.top());  //计算(注意num2和num1的位置,压入栈之后是反过来了)
                    // cout<<sum<<endl;
                    sc.pop(); //删除字符栈的字符
                    num.push(sum);  //压入计算的结果
                }
            }
        }//while2

        cout<<num.top()<<endl;
    }//while1

    return 0;
}

PS:参考某大佬的做法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值