写在前面: 我是「虐猫人薛定谔i」,一个不满足于现状,有梦想,有追求的00后
\quad
本博客主要记录和分享自己毕生所学的知识,欢迎关注,第一时间获取更新。
\quad
不忘初心,方得始终。
\quad❤❤❤❤❤❤❤❤❤❤
设计要求
要求实现一个能进行表达式求值的计算器。

思路分析
用两个栈来实现表达式求值,其中一个是运算符栈,另一个是操作数栈,从左到右扫描表达式,如果是数字则进入操作数栈,如果是运算符,则应根据当前运算符与栈顶运算符的优先级来确定是否入栈。对于左右括号,左括号直接压入操作符栈,当遇到右括号时,将操作符栈中的运算符依次弹出并进行相应的运算,直到遇到左括号。

代码实现
#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <sstream>
using namespace std;
double calcVal(double x, double y, string op);
map<string, int> imap = {
{
"+", 0}, {
"-", 0}, {
"*", 1}, {
"/", 1},{
"(",-1}};
int main()
{
string line;
while (getline(cin, line))
{
istringstream is(line);
stack<string> op;
stack<double> nums;
string ch;
while (is >> ch)
{
if (ch=="(")
{
op.push(ch);
}
else if (ch == ")")
{
string oper = op.top();
while (oper!="(")
{
double x = nums.top();
nums.pop();
double y = nums.top

本文介绍了如何使用C++编写一个计算器,通过两个栈实现表达式求值。思路涉及数字入操作数栈,运算符根据优先级判断入栈,并详细处理括号。代码经过部分测试,但可能存在错误,欢迎讨论指正。文章还提到,未来可考虑增加图形界面以提升用户体验。
最低0.47元/天 解锁文章
3385





