随手记录

自己随便写写的记录

四则运算,加减乘除,带括号小数,负数。

#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
const int max = 10000;
struct zhan
{
	char op[max];
	double num[max];
	int topn;
	int topo;
};
int first(char x)
{
	if (x == '*' || x == '/') return 2;
	else if (x == '+' || x == '-') return 1;
	else if (x == '(') return 0;
}
void main()
{
	zhan pro; pro.topn = -1; pro.topo = -1;//结构体num存数字,op存操作符
	int i, whethernum = 0; double  m, a, b,count = 0, counts = 0;//whethernum用来判断是小数点前还是后,count做多位数总值,counts做小数点后的幂,a,b用来保存栈顶和次栈顶弹出的数字
	char x;
	char str[max];
	gets_s(str);
	for (i = 0; i < strlen(str); i++)
	{
		
		if (str[i] == '(') pro.op[++pro.topo] = str[i]; //若是左括号压入操作符栈顶
		else if (str[i] == '-' || str[i] == '+' || str[i] == '*' || str[i] == '/' || str[i] == ')')
		{
			pro.num[++pro.topn] = count;
			count = 0; counts = 0; whethernum = 0;//若是除左括号外的符号,将count存入数据栈,并将count,counts,whethernum重置为0
			 if (str[i] == ')')
			{
				while (pro.op[pro.topo] != '(')
				{
					b = pro.num[pro.topn--];
					if (pro.topn != -1) a = pro.num[pro.topn--];
					else a = 0;
					x = pro.op[pro.topo--];
					switch (x)
					{
					case '+': m = a + b; count = m; break;
					case '-':m = a - b; count = m; break;
					case '*':m = a*b; count = m; break;
					case '/':m = a / b; count = m; break;
					}
				}
				pro.topo--;
			}//若是右括号,则依次弹出数据栈和操作栈类元素进行计算,直到遇到左括号,将左括号从操作符栈中删除
			else if (first(str[i]) > first(pro.op[pro.topo])||pro.topo==-1) pro.op[++pro.topo] = str[i];//若当前操作符优先级高于栈顶操作符或此时操作符栈内为空,将当前操作符压入操作栈内
			else if (first(str[i]) <= first(pro.op[pro.topo]))
			{
				b = pro.num[pro.topn--]; 
				if(pro.topn!=-1) a = pro.num[pro.topn--];
				else a = 0;
				x = pro.op[pro.topo--];
				switch (x)
				{
				case '+': m = a + b; pro.num[++pro.topn] = m; break;
				case '-':m = a - b; pro.num[++pro.topn] = m; break;
				case '*':m = a*b; pro.num[++pro.topn] = m; break;
				case '/':m = a / b; pro.num[++pro.topn] = m; break;
				}
				pro.op[++pro.topo] = str[i];
			}//若当前操作符优先级小于或等于栈顶操作符,则弹出两个数字和一个操作符进行计算,并将结果重新压入数据栈顶
		}
		else
		{
			if (str[i] == '.') whethernum = 1;
			else if (whethernum==0) count = count * 10 + str[i] - '0';
			else if (whethernum == 1) count = count + pow((double)10, --counts)*(str[i] - '0');
		}//若是数字,多位数计算过程
	}
	pro.num[++pro.topn] = count;//处理最后一个数字
	
	while (pro.topo != -1)
	{
		b = pro.num[pro.topn--];
		if (pro.topn != -1) a = pro.num[pro.topn--];
		else a = 0;
		x = pro.op[pro.topo--];
		switch (x)
		{
		case '+': m = a + b; pro.num[++pro.topn] = m; break;
		case '-':m = a - b; pro.num[++pro.topn] = m; break;
		case '*':m = a*b; pro.num[++pro.topn] = m; break;
		case '/':m = a / b; pro.num[++pro.topn] = m; break;
		}
	}//遍历完后若操作符栈内不为空,则依次弹出并进行计算
	cout << pro.num[0];//输出计算结果
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页