栈实现加减乘除(C++)

加减乘除四则运算可以用栈来模拟实现

需要定义两个栈:

1.符号栈 stack<char> op;

2.数字栈 stack<float> num;

主要设计思想:

通过遍历字符串(s)中所有的内容,分别找出待计算的数字(压入数字栈)和待运算的符号(压入符号栈),同时通过判断符号栈栈顶(op.top())和当前遍历到的符号串中的运算符(s[i++])的优先级谁的更大,决定执行将当前符号压入符号栈(getlevel(op.top()<getlevel(s[i]))或者取出当前符号栈中的栈顶运算符来结合数字栈中的数据进行运算(getlevel(op.top()>=getlevel(s[i]))

具体实现代码如下所示:

#include<iostream>
#include<string>
#include<stack>

using namespace std;

int getlevel(char op)
{
    //符号的优先级
    if(op == '*'||op == '/')
        return 3;
    else if(op == '+'||op=='-')
        return 2;
    else if(op == '$')
        return 1;
    else return 0;
}

float compute(float x,float y,char op)
{
    if(op == '*')
        return x*y;
    else if(op == '/')
        return x/y;
    else if(op == '+')
        return x+y;
    else
        return x-y;
}


int main()
{
    string s;//输入的字符串
    stack<char> op;//符号栈
    stack<float> num;//数字栈
    op.push('#');
    while(cin>>s)
    {
        s+='$';//字符串结尾加一个字符
        int i=0;//用来遍历字符串,记录当前位置下标
        while(i<s.size())
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                string str;
                while(s[i]>='0'&&s[i]<='9' || s[i]=='.')
                    str+=s[i++];
                float res = stof(str);
                num.push(res);
            }
            else
            {
                if(getlevel(op.top())<getlevel(s[i]))
                    op.push(s[i++]);
                else
                {
                    char o = op.top();
                    op.pop();
                    float x2 = num.top();
                    num.pop();
                    float x1 = num.top();
                    num.pop();
                    x1 = compute(x1,x2,o);
                    num.push(x1);
                }
            }
        }
        cout<<num.top()<<endl;
        num.pop();
        op.pop();

    }

    return 0;
}

其中寻找数字的代码块当中实现了对小数进行处理的操作:

if(s[i]>='0'&&s[i]<='9')
            {
                string str;
                while(s[i]>='0'&&s[i]<='9' || s[i]=='.')
                    str+=s[i++];
                float res = stof(str);
                num.push(res);
            }

通过while循环来不断记录属于数字和小数点的内容,存储在str字符串当中。找到所有的信息之后使用stof()函数来将字符串转化成float类型的数据,最后将找到的数据(res)压入数字栈当中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以为您解答这个问题。首先,您需要定义一个栈来存储中间结果和操作符。具体的做法是,读入一个整数或操作符时,如果是整数就直接入,如果是操作符就将其与顶操作符进行比较,如果优先级高于顶操作符,则直接入,否则将顶操作符弹出并进行相应的计算,然后将计算结果入。最终,中只剩下一个整数,即为最终的计算结果。 以下是一个示例代码: ```c++ #include <iostream> #include <stack> #include <string> using namespace std; int priority(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } int calculate(stack<int>& nums, stack<char>& ops) { int num2 = nums.top(); nums.pop(); int num1 = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); switch (op) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; default: return 0; } } int evaluate(string expr) { stack<int> nums; stack<char> ops; for (int i = 0; i < expr.size(); i++) { if (isdigit(expr[i])) { int num = 0, j = i; while (j < expr.size() && isdigit(expr[j])) { num = num * 10 + (expr[j] - '0'); j++; } nums.push(num); i = j - 1; } else if (expr[i] == '(') { ops.push(expr[i]); } else if (expr[i] == ')') { while (ops.top() != '(') { nums.push(calculate(nums, ops)); } ops.pop(); } else if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') { while (!ops.empty() && priority(ops.top()) >= priority(expr[i])) { nums.push(calculate(nums, ops)); } ops.push(expr[i]); } } while (!ops.empty()) { nums.push(calculate(nums, ops)); } return nums.top(); } int main() { string expr = "((2+3)*5-8)/4"; int result = evaluate(expr); cout << result << endl; return 0; } ``` 这段代码实现了带括号的四则混合整数运算,您可以根据自己的需要进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌木_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值