【bitse——四则运算】3.表达式表示与处理——Expression类

作为处理的整体,将表达式封装为类。

实现了多位数运算,随机生成,判断相等,求解等功能。

并且可添加新的运算。

实现思路:

将中缀表达式变为后缀表达式,再进行求解。

中缀变后缀:

扫描字符串,若为数字,则直接放入后缀表达式中。

若为符号,

若优先级高于栈顶符号,则入栈,

若优先级小于栈顶符号,则栈顶符号出栈,放入后缀表达式中,再次尝试。

若优先级相同,为括号,出栈即可。

细节:添加#作为开始结束标志,避免空栈比较。

后缀求解:

扫描后缀表达式,若为数字,入栈。若为符号,从操作数栈中取数计算再入栈。

细节:多位数的处理。

判断相同:

根据题目,当两个串每次运算都相同时,认为相同。故只需同步进行运算,运算前判断运算数是否相同即可。

细节:两表达式的同步,例如 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();
};

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值