⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculate.cpp

📁 可以识别输入的算术表达式并计算机结果
💻 CPP
字号:
#include "Calculate.h"
#include <iostream>
#include <stack>
#include <math.h>
#include <stdlib.h>
using namespace std;
stack<char> p;

char b[40];
int j=0;
int calculate::acf(char m)     //返回运算符在后缀表达式中的优先级别
{
	switch (m)
	{
	case '#': return -1;break;
	case '(': return 1;break;
	case '+':
	case '-': return 3;break;
	case '*':
	case '/': return 5;
	}
	return 0;
}
void calculate::covert1(char q)  //中缀转后缀中关于'+'和'-'的执行过程
{
	
	while(acf(q)<acf(p.top()))
		{   
		
			b[j++]=p.top();
			b[j++]=' ';
			p.pop();
		}
		p.push(q);
	
	
}
char* calculate::covert()         //中缀表达式转后缀表达式
{   
	p.push('#');                  //堆栈p结束标志
	for(int i=0;i<a.length();i++)
	{
		if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'||a[i]=='('||a[i]==')')
			b[j++]=' ';
		switch (a[i])
		{
		case '+':
		case '-':  covert1(a[i]);break;
		case '*':
		case '/':  	
		case '(':  p.push(a[i]);break;
		case ')':  
				while (p.top()!='(')
				{
					b[j++]=p.top();
					b[j++]=' ';
					p.pop();
				}
				p.pop();break;
		default: {
			b[j++]=a[i];
		
				 }
		}

	}
	b[j++]=' ';
	while(p.top()!='#')
	{
		b[j++]=p.top();
		b[j++]=' ';
		p.pop();
	}
	return b;
}
calculate::~calculate()
{
}
float calculate::count()    //计算后缀表达式
{
	stack<float>counter;
	float first,second,n;
	for(int i=0;i<strlen(b);i++)
	{
		if(b[i]==' ')continue;

		if(b[i]=='*'||b[i]=='-'||b[i]=='+'||b[i]=='/')
		{
			if(!counter.empty())
			{
				first=counter.top();
				counter.pop();
			}else {cout<<"Expression err!"<<endl;
			       exit(0);
			}
			if(!counter.empty())
			{     
				
				second=counter.top();
 				counter.pop();
			}else{
				cout<<"Expression err!"<<endl;
			 exit(0);
			}
			switch(b[i])
			{
			case '+':  n=first+second; break;
			case '-':  
				if(b[i+2]=='-')
				{
					n=second+first;
					break;
				}
			    n=second-first;
				break;
			case '*':  n=second*first; break;
			case '/':  if(first!=0)
						   n=second/first;
				else {
					cout<<"Err:Divide by 0!"<<endl;
					exit(0);
					}
			}
			counter.push(n);

		}
		else{
			counter.push(atof(b+i));
			while(*(b+i)!=' ')i++;
		}
	}
	return (counter.top());
}
calculate::calculate()
{
	cout<<"Please input expression:"<<endl;
	cin>>a;
//	cout<<endl<<a<<endl;
}
string calculate::get_a()
{
	return a;
}
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -