C语言实现简易计算器(二)

接上一篇文章:C语言实现计算器(一)

该程序较上一篇复杂,但功能比较齐全,可以实现带括号的计算,但仍不能实现带小数点的运算

#include <stdio.h>
#include <stdlib.h>
#define max 2014
int createstack(int *operand,int * top1,int num)//数字压入数字栈
{
	(*top1)++;
	operand[*top1] = num;//保存数字
	return 0;
}
int insert_oper(char * oper,int *top2,char ch)//运算符压入符号栈
{
	(*top2)++;
	oper[*top2] = ch;//保存运算符
	return 0;
}
int compare(char *oper,int *top2,char ch)//比较运算优先级
{  
	if((oper[*top2] == '-' || oper[*top2] == '+')&&(ch == '*' || ch == '/'))//判断当前优先级是否比栈顶运算符优先级高
	{
		return 0;//运算符压入栈
    }
	else if(*top2 == -1 || ch == '(' || (oper[*top2] == '(' && ch != ')'))//判断运算符栈是否为空
    {
		return 0;
	}
	else if (oper[*top2] =='(' && ch == ')' )//判断括号内的表达式是否计算完毕
	{
		(*top2)--;
		return 1;//对括号进行处理
	}
	else
	{
		return -1;//进行运算符的运算
	}
}
int Operation(int *operand,char *oper,int *top1,int *top2)//对数字进行运算
{
	int a = operand[*top1];
	int b = operand[*top1 - 1];
	int x = 0;
	if(oper[*top2] == '+')
	{
		x = a + b;
	}
	else if(oper[*top2] == '-')
	{
		x = b - a;
	}
	else if(oper[*top2] == '*')
	{
		x = b * a;
	}
	else if(oper[*top2] == '/')
	{
		x = b / a;
	}
	(*top1)--;//将数据栈顶下移一位
	operand[*top1] = x;//将得到的值压入数字栈
	(*top2)--;//将运算符栈顶下移一位
}
int main()
{
	int operand[max] = {0};
	int  top1 = -1;
	char oper[max] = {0};
	int top2 = -1;
	char *str = (char *)malloc(sizeof(char) * 100);
	scanf("%s",str);
	char* temp;
	char dest[max];
	int num = 0;
	int i = 0;
	while(*str != '\0')
	{
		temp = dest;
		while(*str >= '0' && *str <= '9')//判断是否是数字
		{
			*temp = *str;
			str ++;
			temp ++;           
		}//遇到符号退出
		if(*str != '(' && *(temp - 1) != '\0')//判断符号是否为左括号'('
		{
			*temp = '\0';
			num = atoi(dest);//将字符串转为数字
			createstack(operand,&top1,num);//将数据压入数字栈
			}
		while(1)
		{
			 i = compare(oper,&top2,*str);//判断运算符优先级
			 if(i == 0)
			{
				insert_oper(oper,&top2,*str);//压入运算符栈
				break;
			}
			else if(i == 1)//判断括号内的表达式是否结束
			{
				str++;
			}
			else if(i == -1)//进行数据处理
			{
				Operation(operand,oper,&top1,&top2);
			}
		}
		str ++;//指向表达式下一个字符
	}
	printf("计算结果为: %d\n",operand[0]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Sundial_dream/article/details/81272749