作为处理的整体,将表达式封装为类。
实现了多位数运算,随机生成,判断相等,求解等功能。
并且可添加新的运算。
实现思路:
将中缀表达式变为后缀表达式,再进行求解。
中缀变后缀:
扫描字符串,若为数字,则直接放入后缀表达式中。
若为符号,
若优先级高于栈顶符号,则入栈,
若优先级小于栈顶符号,则栈顶符号出栈,放入后缀表达式中,再次尝试。
若优先级相同,为括号,出栈即可。
细节:添加#作为开始结束标志,避免空栈比较。
后缀求解:
扫描后缀表达式,若为数字,入栈。若为符号,从操作数栈中取数计算再入栈。
细节:多位数的处理。
判断相同:
根据题目,当两个串每次运算都相同时,认为相同。故只需同步进行运算,运算前判断运算数是否相同即可。
细节:两表达式的同步,例如 1 2 3 + +与2 3 + 1 +是相同的,不能直接取几个数之后进行计算。而应分别扫描至下一个符号。
关键属性:
静态:
maxNumber,题目中最大的数字。
opNumber,运算总数。
powerSetting,true 使用^,false 使用 **
opcmp 优先级表。
op 操作符。
非静态:
problemExpression,题目串。
postfixExpression,后缀串。
stack_opnum,求解时使用的操作数栈。
stack_op,转后缀时使用的操作符栈。
ans,答案。
关键方法:
构造函数,无参则随机构造,或传入题目字符串。
getAns(),获取答案。
#pragma once
#include <string>
#include "Number.h"
#include <stack>
class Expression
{
private:
//true 使用^,false 使用 **
//true 使用分数表示 false 使用小数表示。
static bool fractionSetting;
//最大数字
static const int maxNumber = 100;
//运算总数。
static const int opNumber = 8;
//题目字符串
std::string problemExpression;
//后缀表达式。
std::string postfixExpression;
std::stack<Number> stack_opnum;
std::stack<char> stack_op;
//标准答案
Number ans;
//运算优先级矩阵。
static const int opcmp[opNumber][opNumber];
static const char op[opNumber];
void init();
int cmp(char first, char second);
int processChar(char ch);
int processOperator(char ch);
int infixToPostfix();
int calculate();
public:
static bool powerSetting;
bool compare(Expression obj);
//随机生成表达式。
Expression();
std::string randExpression();
//输入表达式。
Expression(std::string expression);
std::string getProblemExpression();
Number getAns();
//
~Expression();
};