C++实现算数表达式的计算及容错(基于后缀表达式思想)

这篇博客介绍了如何使用C++实现基于后缀表达式的算术表达式计算,包括处理小数、负数和括号。通过两个栈分别保存操作符和数字,对输入表达式进行错误检测,如除以零、格式错误和括号匹配,并详细解释了操作符优先级的处理策略。

数据结构课程实验设计的作业:

[问题描述]
  一个算术表达式是由操作数(operand)、运算符(operator)和界限符(delimiter)组成的。假设操作数是正实数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:#(7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“运算符优先法”求算术表达式的值。
[基本要求]
(1) 从键盘或文件读入一个合法的算术表达式,输出正确的结果。
(2) 显示输入序列和栈的变化过程。
(3) 考虑算法的健壮性,当表达式错误时,要给出错误原因的提示。

思路:
这个实验主要是针对字符串的操作。基于前面四个实验,已经能够熟悉String字符串的很多操作,所以选择了这个实验。这个实验可以使用两个栈来进行操作,一个栈用来保存操作符,另一个栈用来保存数字。即使用后缀表达式的思想来计算。这个程序的功能支持小数输入、负数输入、输出等。为了实现方便,使用了标准库中的stack,cmath,string,程序在逻辑上可以分为两块,一块是运算出栈,一块是入栈

流程:
1.输入:跟熟悉的可输入多项数据的计算器一样,输入一串算数表达式,将输入的数据用String进行保存起来。
2.操作:先对字符串进行检错,如:是否被除以0,是否式子的格式不对,是否括号不匹配等等,都需要检测出来。接着,遍历整个字符串,创建一个函数来进行判断在字符串的这个位置的字符是否属于操作符还是数字。如果属于操作符的话,则要进行判断:a. 如果保存操作符的栈为空,直接插入操作符 b. 如果该操作符为左括号,不做任何判断放入栈中 c. 如果操作符栈中存在操作符的话,那么,要判断栈顶的操作符的优先级别。如果栈顶的优先级别高于当前的操作符的话,那么则要“踢出”这个栈顶的操作符,在看看栈顶的操作符的优先级别是否高于当前操作符,如果还高,再“踢出”这个操作符。直到栈顶没有比当前操作符优先的操作符或者栈顶为空的操作符。为了记住这个方式,可以用形象的比喻:

将要入栈的操作符比喻成一头公狮子,这头狮子不容许门卫驻扎了其它更强的狮子,想要进入入的房子(栈)保存了许多其它的狮子,如果这一头狮子想要进来这个房子(栈),要么打败门卫驻守的狮子(栈顶),要么门卫驻守的狮子害怕他(优先级别比要入栈的操作符低),让他直接进去。但是,可能打败了门卫,房子里还有另外的狮子出来驻守,要么让要进去房子里的狮子打败门卫,直到打到房子里面没有任何一头狮子,要么威吓他们(要进去的算数操作符优先级比栈顶的高),直接进去。要进去房子的狮子选择“能忍则忍”,能征服他们绝不击败他们,反正…倔强的狮子一定要进去。

所以这就是这个原理(虽然比喻很不恰当),每次踢出去的狮子(操作符),都从数据栈中拿出两个数来,进行计算即可。

结构:
在这里插入图片描述

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

//判断输入的字符是操作符还是数字还是‘.’,如果是操作符,返回true,否则返回false
bool judgeOperation(char targetChar) {
    //将输入的字符转为ascii码,以便进行判断
    int ascChar = (int) targetChar;

    return !((48 <= ascChar && ascChar <= 58) || ascChar == '.');
}

//检查输入是否合法
bool checkValid(string inputData) {
    bool status = true;
    bool includingNum = false;
    bool includingOperation = false;
    //1.检查括号是否匹配
    int rightK, leftK;
    rightK = leftK = 0;
    for (char i : inputData) {
        if (i == '(') {
            ++leftK;
        } else if (i == ')') {
            ++rightK;
        }
    }

    if(rightK != leftK){
        cout<<" 错误,括号不匹配!"<<endl;
        status = false;
    }

    //2.检查是否有除以0
    for (int j = 0; j < inputData.length(); ++j) {
        if(inputData[j] == '/' && j+1 < inputData.length() && inputData[j+1] == '0'){
            if(!(j+2 < inputData.length() && inputData[j+2] == '.')){
                cout<<" 错误,除数为0!"<<endl;
                status = false;
            }
        }

        if(inputData[j] == '+' || inputData[j] == '-' || inputData[j] == '*' || inputData[j] == '/'){
            includingOperation = true;
            if(j + 1 == inputData.length()){
                cout<<" 错误,算数符后面为空!"<<endl;
                status = false;
            }else if(inputData[j + 1] == '+' || inputData[j + 1] == '-' || inputData[j + 1] == '*' || inputData[j + 1] == '/'){
                cout<<" 错误,算数符后面为算数符!"<<endl;
                status = false;
            }
        }

        if((48 <= (int)inputData[j+1] && (int)inputData[j+1] <= 57 )){
            includingNum = true;
        }
    }

    if(!includingNum){
        cout<<" 错误,不包含数字!";
        status = false;
    }

    if(!includingOperation){
        cout<<" 错误,不包含操作符!"<< endl;
        status = false;
    }

    return status;
}

//比较传入两个字符的优先级大小,如果第一个优先级更大的话,则返回true,否则返回false
int compareWeight(char firstChar, char secondChar) {
    int firstWeight, secondWeight;

    //对第一个字符获取优先级
    if(firstChar == '#'){
        firstWeight = -1;
    } else if (firstChar == '(') {
        firstWeight = 0;
    } else if (firstChar == '+' || firstChar == '-') {
        firstWeight = 1;
    } else if (firstChar == '*' || firstChar == '/') {
        firstWeight = 2;
    } else {
        cout << "输入的字符有误!" << endl;
        exit(-1);
    }

    //对第二个字符获取优先级
    if (secondChar == '#') {
        secondWeight = -1;
    } else if (secondChar == '('){
        secondWeight = 0;
    } else if (secondChar == '+' || secondChar == '-') {
        secondWeight = 1;
    } else if (secondChar == '*' || secondChar == '/') {
        secondWeight = 2;
    } else {
        cout << "输入的字符有误!" << endl;
        exit(-1);
    }

    return firstWeight > secondWeight;
}

//从数字栈中弹出两个数,从操作符栈中弹出一个符号来进行操作
void computeChar(stack<double> &stackDoubleBoxer, stack<char> &stackOperationBoxer, double &result) {
    double secondNum = stackDoubleBoxer.top();
    stackDoubleBoxer.pop();

    double firstNum = stackDoubleBoxer.top();
    stackDoubleBoxer.pop();

    switch (stackOperationBoxer.top()) {
        case '+':
            firstNum += secondNum;
            break;
        case '-':
            firstNum -= secondNum;
            break;
        case '/':
            firstNum /= secondNum;
            break;
        case '*':
            firstNum *= secondNum;
            break;
        default:
            cout<<"发生错误了!"<<endl;
            exit(-1);
    }
    stackOperationBoxer.pop();
    result = firstNum;
    stackDoubleBoxer.push(result);
}

//对字符进行操作
void operationDeal(char &targetChar, stack<char> &stackOperationBoxer, stack<double> &stackDoubleBoxer,
        int &targetPosition, double &result) {
    //1.如果是左括号的话,直接入字符栈
    if (targetChar == '(') {
        stackOperationBoxer.push(targetChar);

        ++targetPosition;
        return;
    }

        //2.如果是右括号的话
    else if (targetChar == ')') {
        while (stackOperationBoxer.top() != '(' && !stackOperationBoxer.empty()) {
            computeChar(stackDoubleBoxer, stackOperationBoxer, result);
        }
        //退去左括号
        stackOperationBoxer.pop();
        ++targetPosition;
        return;
    }

        //3.如果是其他字符的话,即加减乘除
    else if (targetChar == '+' || targetChar == '-' || targetChar == '*' || targetChar == '/') {
        //3.1如果没有栈顶元素的话
        if(stackOperationBoxer.empty()){
            stackOperationBoxer.push(targetChar);
        }
            //3.2如果有栈顶元素且栈顶优先级低的话
        else if (compareWeight(targetChar, stackOperationBoxer.top())) {
            stackOperationBoxer.push(targetChar);
        }
            //3.3如果该字符的优先级与栈顶元素相等或者小的话
        else {
            //3.3.1依次将栈顶元素弹出计算
            do{
                computeChar(stackDoubleBoxer, stackOperationBoxer, result);
            }while (!stackOperationBoxer.empty() && !compareWeight(targetChar, stackOperationBoxer.top()));
            stackOperationBoxer.push(targetChar);
        }
    }

        //4.发生错误的话
    else {
        cout << "输入的字符有误!" << endl;
        exit(-1);
    }

    ++targetPosition;
}

//对数字进行操作,与对字符操作不同的是,字符操作每次处理一个字符,而这个函数每次处理多个组成数字的字符
void doubleDeal(string inputData, int &targetPosition, stack<double> &stackDouble) {
    //记录小数偏移量
    int doubleMove = 1;
    double result = 0.0;

    //小数点前面的处理
    while (targetPosition < inputData.length() && !judgeOperation(inputData[targetPosition]) && inputData[targetPosition] != '.') {
        result *= 10;
        result += (double) (inputData[targetPosition] - 48);
        ++targetPosition;
    }

    //小数点后面的处理
    if(targetPosition < inputData.length() && !judgeOperation(inputData[targetPosition]) && inputData[targetPosition] == '.'){
        ++targetPosition;
        do{
            result += pow(0.1, doubleMove) * (double) (inputData[targetPosition] - 48);
            ++doubleMove;
            ++targetPosition;
        }while(targetPosition < inputData.length() && !judgeOperation(inputData[targetPosition]));
    }

    stackDouble.push(result);
}

//计算
void computeString(string inputData) {
    //初始化,创建两个栈,一个用来存储操作符,一个用来存储数字
    stack<char> stackOperationBoxer;
    stack<double> stackDoubleBoxer;
    double result = 0.0;

    //检测输入的字符串是否为空
    if (inputData.empty()) {
        cout << "错误!输入的字符串为空!";
        return;
    }

    //(1)开始进行主程序
    int targetPosition = 0;
    while (targetPosition < inputData.length()) {
        //1.先判断所操作字符是符号还是数字
        bool isOperation = judgeOperation(inputData[targetPosition]);

        //2.如果是字符的话
        if (isOperation) {
            operationDeal(inputData[targetPosition], stackOperationBoxer, stackDoubleBoxer,targetPosition, result);
        }

            //3.如果是数字的话
        else {
            doubleDeal(inputData, targetPosition, stackDoubleBoxer);
        }
    }

    //(2)结尾工作,将栈中剩余的元素全部计算
    while(!stackOperationBoxer.empty()){
        computeChar(stackDoubleBoxer, stackOperationBoxer, result);
    }

    cout<<"计算结果为:";
    cout << result;
}

int main() {
    string inputData;
    while(cout << "请输入字符串表达式子:" && cin>>inputData){
        if(checkValid(inputData)){
            computeString(inputData);
        }else{
            continue;
        }
        cout<<endl;
    }
}

结果:

在这里插入图片描述
在这里插入图片描述
为了进行简化和方便输入,我取消了在式子输入头尾中加入的“#”,经过反复的测试,测试式子运算的结果全部正确,但不排除我没有想到的格式,可能还存在bug没有修复。同时,在代码中,使用了大量的if语句来进行分支判断。可以再继续想办法简化代码。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值