计算器(带括号)

本文介绍了一种算法,用于将数学表达式的中缀表示转换为后缀表示,并提供了计算后缀表达式的功能。通过使用栈数据结构,文章详细解释了如何解析输入的中缀表达式,将其分割成元素列表,然后应用运算符优先级规则来生成等效的后缀表达式。最后,文章展示了如何利用栈来高效地计算后缀表达式的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream> //for cout endl
#include<stack> //for stack
#include<string>// for string
#include<vector>// for vector
#include<algorithm> //for pow()
using namespace std;
int computeSuffix(vector<string>);//计算后缀表达式 int整数可多于1位 + - * /
bool priority(string a, string b);//辅助函数 判断两个运算符的优先级
int str2dec(string);//字符串转int
vector<string> str2str(const string&);//无空格运算表达式分割
vector<string> infix2suffix(const vector<string>&);//分割后的字符串中缀转后缀
int main()
{
    string str;
    while(cin>>str)
    {
        vector<string> str1=str2str(str);
        str1=infix2suffix(str1);
        cout<<computeSuffix(str1)<<endl;
    }
    return 0;
}
int computeSuffix(vector<string> str)
{
    int size = str.size();
    stack<int> st;
    for(int i = 0; i < size; i++)
    {
        if(str[i] != "+"&&str[i] != "-"&&str[i] != "*"&&str[i] != "/")
            st.push(str2dec(str[i]));
        if(str[i] == "+")
        {
            int a = st.top();
            st.pop();
            int b = st.top();
            st.pop();
            st.push(a + b);
        }
        if(str[i] == "-")
        {
            int a = st.top();
            st.pop();
            int b = st.top();
            st.pop();
            st.push(b - a);
        }
        if(str[i] == "*")
        {
            int a = st.top();
            st.pop();
            int b = st.top();
            st.pop();
            st.push(a * b);
        }
        if(str[i] == "/")
        {
            int a = st.top();
            st.pop();
            int b = st.top();
            st.pop();
            st.push(b / a);
        }
    }
    return st.top();
}
int str2dec(string str)
{
    int size = str.size();
    int res = 0;
    for(int i = 0; i < size; i++)
        res += (str[i] - '0')*pow(10, size-i-1);
    return res;
}
vector<string> str2str(const string& str)
{
    int size = str.size();
    vector<string> res;
    string temp;
    for(int i = 0; i < size; i++)
    {
        if(str[i] != '+'&&str[i] != '-'&&str[i] != '*'&&str[i] != '/'&&str[i]!='('&&str[i]!=')')
            temp += str[i];
        if(str[i] == '+')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back("+");
        }
        if(str[i] == '-')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back("-");
        }
        if(str[i] == '*')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back("*");
        }
        if(str[i] == '/')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back("/");
        }
        if(str[i] == '(')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back("(");
        }
        if(str[i] == ')')
        {
            if(!temp.empty())
            {
                res.push_back(temp);
                temp.clear();
            }
            res.push_back(")");
        }
        if(i == size - 1&&!temp.empty())
            res.push_back(temp);
    }
    return res;
}
vector<string> infix2suffix(const vector<string>& s)
{
    vector<string> res;
    stack<string> st;
    int size = s.size();
    for(int i = 0; i < size; i++)
    {
        if(s[i] != "("&&s[i] != ")"&&s[i] != "+"&&s[i] != "*"&&s[i] != "-"&&s[i]!="/")
            res.push_back(s[i]);//数字直接放入算术表达式
        if(s[i] == "(")
            st.push(s[i]);//'('左括号直接入栈
        if(s[i] == "+"|| s[i] == "*"|| s[i] == "-"||s[i]=="/")//+ -*/
        {
            if(st.empty())
                st.push(s[i]);//栈空 算术符号入栈
            else//否则根据算术符号优先级出栈
                while(1)
                {
                    string temp = st.top();//栈顶算术符号
                    if(priority(s[i], temp))//栈顶算术符号优先级高于当前算术符号
                    {
                        st.push(s[i]);//入栈
                        break;//出循环
                    }
                    else
                    {
                        res.push_back(temp);//否则栈顶算术符号放入算术表达式
                        st.pop();//直到当前算术符号优先级小于栈顶算术符号
                        if(st.empty())//如果栈空 那么当前算术符号入栈
                        {
                            st.push(s[i]);
                            break;//出循环
                        }
                    }
                }
        }
        if(s[i] == ")")//如果是右括号
        {
            while(st.top() != "(")//算术符号出栈 直到栈顶为左括号
            {
                res.push_back(st.top());
                st.pop();
            }
            st.pop();//'('出栈 且不放入算术表达式
        }
    }
    while(!st.empty())//栈中剩余算术符号放入算术表达式
    {
        res.push_back(st.top());
        st.pop();
    }
    return res;//转换后的算术表达式
}
bool priority(string a, string b)
{
    //算术优先级a>b 返回true 这里注意(优先级低于所有的运算符
    if(a == "+")
    {
        if(b == "(")
            return true;
        else
            return false;
    }
    if(a == "-")
    {
        if(b == "(")
            return true;
        else
            return false;
    }
    if(a == "*")
    {
        if(b == "+"|| b == "-"|| b=="(")
            return true;
        else
            return false;
    }
    if(a == "/")
    {
        if(b == "+"|| b == "-"|| b == "(")
            return true;
        else
            return false;
    }
    return false;//语法要求必有返回值
}

 

### C语言实现支持括号和三角函数的计算器 为了创建一个能够处理复杂算术运算(包括括号和三角函数)的计算器,可以采用词法分析器(Lexical Analyzer)与语法解析器(Parser),通过`flex`和`bison`工具来简化开发过程。下面展示了一个基于这些技术构建的支持基本四则运算以及正弦(`sin`)、余弦(`cos`)功能的小型应用程序。 #### 主要文件结构说明: - `calc.y`: 定义语法规则及相应动作; - `calc.l`: 描述标记模式及其对应的C代码片段; - `functions.c/h`: 提供额外数学操作的具体实现; #### 关键点概述: 1. **引入必要的头文件** 需要在`.y`文件顶部加入标准库声明以便访问内置数学函数。 ```c #include <math.h> ``` 2. **扩展文法定义** 更新Bison规则以识别新的关键字如`sine`, `cosine`等,并允许嵌套子表达式的存在形式即圆括号内的任意合法组合[^1]。 3. **自定义辅助方法** 创建独立模块用于封装特定算法逻辑,比如角度转弧度转换或是调用实际API完成具体数值求解工作。 4. **集成第三方组件** 当遇到像幂次方这样的特殊情形时,记得链接相应的动态共享对象(-lm选项)[^1]。 5. **完整的源码实例** ```c // calc.y部分摘录 %token NUMBER SIN COS LPAREN RPAREN ADD SUB MUL DIV POW EOF %% input: /* empty */ | input line ; line: '\n' | exp '\n' { printf("%f\n", $1); } ; exp: factor {$$ = $1;} | exp ADD factor {$$ = $1 + $3;} | exp SUB factor {$$ = $1 - $3;} ; factor: term {$$ = $1;} | factor MUL term{$$ = $1 * $3;} | factor DIV term{$$ = $1 / $3;} | factor POW term{ $$ = pow($1,$3);} ; term: NUMBER {$$ = atof(yytext);} | SIN '(' exp ')' {$$ = sin($3);} | COS '(' exp ')' {$$ = cos($3);} | LPAREN exp RPAREN {$$=$2;} ; ``` 6. **编译指令汇总** 遵循如下命令序列可顺利完成整个项目的组装部署流程: ```bash cd path/to/project/directory bison -d calc.y flex calc.l gcc -o calc lex.yy.c calc.tab.c functions.c -lm ./calc ``` 7. **测试样例验证** 启动程序后尝试输入类似`(sin(0)+cos(pi()))*2^(log(8)/log(2))`这样复杂的混合式子来进行全方位的功能检测。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值