Calculates the value of a string expression enclosed in parentheses

       Input a correct string, which can contain numbers, decimal points, operation symbols and parentheses, calculate and output the calculation result of the expression.

For example:

  • Input Expression 3.4 Output 3.40
  • Input expression: 7+8.3 Output: 15.30

Input sample column:

3+4.5*(7+2)*(3)*((3+4)*(2+3.5)/(4+5))-34*(7-(2+3))

Output samples:

454.75

#include <iostream>
#include <algorithm>
#include <stack>
#include <cstdlib>
#include <cstring>
using namespace std;

int index=0,len;  //当前运算到什么位置,字符串长度
char a[100];

//遇见乘除法的时候先将乘除法计算后再压入栈,最后栈里面就只有加减法
//遇见括号后就递归,算出括号里面的值

double cul(double b,double c,char ch)  //计算 b 运算符 c的值,如1+2
{
    switch(ch)
    {
        case '+': return b+c;break;
        case '-': return b-c;break;
        case '*': return b*c;break;
        case '/': return b/c;
    }
}

void putNum(stack<double>& b,stack<char>& c,double num)  //将数字压入栈
{

    if(c.empty())
    {
        b.push(num);
        return;
    }
    char ch=c.top();
    if(ch=='*'||ch=='/')   //如果最近一个运算符是*或/,那就计算后再压入栈,保证运算符栈里面只有+ -
    {
        double de=b.top();
        b.pop();
        c.pop();
        b.push(cul(de,num,ch));
    }
    else b.push(num);
}

double allcul(stack<double>& num,stack<char>& op)  //计算栈里面的值,只有加减法
{
    if(op.empty())
    {
        double de=num.top();
        num.pop();
        return de;
    }
    else
    {
        char ch=op.top();
        double de=num.top();
        num.pop();
        op.pop();
        return cul(allcul(num,op),de,ch);
    }
}

double info()
{
    stack<double> num;      //存储数字
    stack<char> operation;  //运算符

    num.push(0);   //数字栈第一个压入0,可以保证负数的运算,如第一个是数字-3,计算时就会变成 0-3

    for(;index<len&&a[index]!=')';)  //未超出范围且没有遇见右括号
    {
        if(a[index]>='0'&&a[index]<='9')  //数字
        {
            double curNum=atof(&a[index]);

            putNum(num,operation,curNum);

            while(a[index]>='0'&&a[index]<='9') index++;
        }
        else if(a[index]!='(')  //运算符
        {
            operation.push(a[index]);
            index++;
        }
        else  //左括号,通过递归,算出括号里面的值
        {
            index++;
            putNum(num,operation,info());
        }
    }
    index++;
    return allcul(num,operation);   //计算所有的值

}

int main()
{
    cin>>a;
    len=strlen(a);
    cout<<info()<<endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_65120254/article/details/124065821