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;
}

 

  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值