// lzy 2018.7.29 于东北大学
//仅代表东北大学最低编程水平,才疏学浅,欢迎各位参考指摘!
//编写了一个十分简易的计算器
//实现了多位,多项正整数的加减乘除运算,没有识别匹配括号或小数的部分
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
//定义了栈数据类型,基于两个栈(数据栈和符号栈)进行运算
class Stack
{
public:
Stack()
{
length = 0;
}
~Stack()
{
}
void Pop()
{
Data[--length] = NULL;
};
//入栈函数1 用于将符号推入符号栈
void Push(char a)
{
Data[length++] = a;
};
//入栈函数2 用于将由字符串转换得到的整数推入数据栈
void Push(int a)
{
Data[length++] = a;
};
//入栈函数3 用于从字符形式的表达式中得到整数,并推入栈
void Push(char a[], int &loc)
{
int count = 0;
int element = 0;
while (a[loc + count] >= '0' && a[loc + count] <= '9')
{
count++;
}
for (int i = 1; i <= count; i++)
{
element += (a[loc + i-1] - '0') * pow(10, count-i);
}
Data[length++] = element;
loc += count;
};
int Data[50];
int length;//用于记录,定位字符串中元素
};
int Calculate(char equation[])
{
Stack num, opt;
int i = 0;
//再结束循环条件到来前,一次遍历输入表达式中各项
while (1)
{
//遍历到数字项,定位完整数字位并转换位整数,推入栈
if (equation[i] >= '0' && equation[i] <= '9')
{
num.Push(equation, i);
if (equation[i] == NULL) break;
continue;
}
//遍历到‘+’或‘-’,优先级较低,直接推入栈
if (equation[i] == int('+') || equation[i] == int('-'))
{
opt.Push(equation[i++]);
continue;
}
//遍历到‘*’或‘/’,优先级较高,先将符号两边的数值进行相应计算,并将结果推入栈
//即到运算操作时,符号栈中不存在‘*’或‘/’符号;‘*’和‘/’只在栈顶出现
if(equation[i] == int('*') ||equation[i] == int('/'))
{
opt.Push(equation[i]);
int t = i + 1;
num.Push(equation,t);
int temp = 0;
if(equation[i] == '*')
temp = num.Data[num.length - 1] * num.Data[num.length - 2];
else if(equation[i] == '/')
temp = num.Data[num.length - 2] / num.Data[num.length - 1];
num.Pop();
num.Pop();
opt.Pop();
num.Push(temp);
i = t;
if (equation[i] == NULL) break;
}
}
//temp用于存储计算结果
int temp = 0;
//在这里,所有乘除运算都已结束,结果作为数值存入了数据栈
//符号栈中只存在‘+’或‘-’
while (opt.length != 0 && num.length != 0)
{
if (opt.Data[opt.length - 1] == '+')
temp += num.Data[num.length - 1];
else if (opt.Data[opt.length - 1] == '-')
temp -= num.Data[num.length - 1];
num.Pop();
opt.Pop();
continue;
}
return num.Data[0] + temp;
}
int _tmain(int argc, _TCHAR* argv[])
{
char a[50];
cout << "Input equation:";
cin >> a;
cout << endl << a << "=" << Calculate(a) << endl;
system("pause");
return 0;
}