You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C++后缀表达式求值代码使其支持多位数运算

实现多位数后缀表达式求值的修改方案

核心问题分析

原来的代码存在两个核心限制:

  • 栈的类型定义错误:使用stack<char>只能存储单字节数值,无法保存多位数的计算结果
  • 每次只读取单个字符作为数字,没有处理连续数字的拼接逻辑

另外,多位数的后缀表达式必须使用分隔符(通常为空格)区分每个运算元素,否则会出现数字歧义(例如连续的123无法判断是1、2、3三个数字还是12、3或者1、23),我们默认修改后的输入格式为空格分隔的后缀表达式,例如"12 3 4 + *"代表中缀的12*(3+4)。

具体修改步骤

  1. 修正栈的类型为stack<float>,用于存储任意大小的数值
  2. 遍历字符串时,遇到数字就持续读取后续连续的数字字符,拼接为完整的数值后再入栈
  3. 遇到空格分隔符直接跳过,不做处理
  4. 遇到运算符时保持原来的出栈计算逻辑不变

修改后的完整代码

#include <iostream>
#include <stack>
#include <string>
#include <cctype> // 用于isdigit、isspace函数

using namespace std;

float calc(float o1,float o2,char c)
{
    if(c=='+') return o1+o2;
    if(c=='-') return o1-o2;
    if(c=='*') return o1*o2;
    if(c=='/') return o1/o2;
    else return 0;
}

float evaluate(string exp)
{
    stack<float> s; // 修正栈类型为float
    int len = exp.length();
    for(int i=0; i<len; i++)
    {
        // 跳过空格分隔符
        if(isspace(exp[i])) {
            continue;
        }
        // 处理多位数
        else if(isdigit(exp[i]))
        {
            float num = 0;
            // 持续读取连续的数字字符,拼接为完整数值
            while(i < len && isdigit(exp[i])) {
                num = num * 10 + (exp[i] - '0');
                i++;
            }
            // 回退一位,抵消外层for循环的i++
            i--;
            s.push(num);
        }
        // 处理运算符
        else
        {
            float o2 = s.top();
            s.pop();
            float o1 = s.top();
            s.pop();
            float result = calc(o1, o2, exp[i]);
            s.push(result);
        }
    }
    return s.top();
}

int main()
{
    // 测试用例:12*(3+4) = 84,对应的后缀表达式为"12 3 4 + *"
    string exp = "12 3 4 + *";
    cout << evaluate(exp) << endl;
    return 0;
}

扩展说明

如果需要支持带小数的浮点数运算,可以在数字读取逻辑中增加对.字符的处理,单独计算小数部分的数值即可。


内容的提问来源于stack exchange,提问作者mahmoud adel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:51:02