#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
//栈
typedef struct{
char data[100];
int top;
}SeqStack,*PStack;
PStack Init_SeqStack(void)
{
PStack p;
p=(PStack)malloc(sizeof(SeqStack));
if(p)
p->top=-1;
return(p);
}
void Push_SeqStack(PStack s,char x)
{
s->top++;
s->data[s->top]=x;
}
void Pop_SeqStack(PStack S,char *x)
{
*x=S->data[S->top];
S->top--;
}
int GetTop_SeqStack(PStack S,char *x)
{
*x=S->data[S->top];
return 1;
}
void Destroy_SeqStack(PStack *S)
{
if(*S)
free(*S);
*S=NULL;
return ;
}
//判断是否是数字
int IsNum(char c)
{
if(c>='0'&&c<='9')
return(1);
else
return(0);
}
//判断优先级
int priority(char op)
{
switch(op)
{
case '=':return(1);
case ')':return(2);
case '+':
case '-':return(3);
case '*':
case '/':return(4);
case '(':return(5);
default:return(0);
}
}
//将infixexp[]中的中缀表达式转化成后缀表达式存入postfixexp[]中
void infix_exp_value(char*infixexp,char*postfixexp)
{
PStack S;
char c,w,topelement;
S=Init_SeqStack();
if(!S)
{
printf("栈初始化失败!");
}
Push_SeqStack(S,'#');
w=*infixexp;
while((GetTop_SeqStack(S,&c),c)!='#'||w!='#')
{
if(IsNum(w))
{
*postfixexp=w;
postfixexp++;
w=*(++infixexp);
}
else
{
if((GetTop_SeqStack(S,&c),c)=='('&&w==')')
{
Pop_SeqStack(S,&topelement);
w=*(++infixexp);
}
else
if((GetTop_SeqStack(S,&c),c)=='('||priority((GetTop_SeqStack(S,&c),c))<priority(w))
{
Push_SeqStack(S,w);
w=*(++infixexp);
}
else
{
Pop_SeqStack(S,&topelement);
*postfixexp=topelement;
postfixexp++;
}
}
}
*postfixexp='#';
*(++postfixexp)='\0';
Destroy_SeqStack(&S);
}
//计算
double postfix_exp(char *A)
{
PStack S;
char Result;
char a,b,c;
char ch;
ch=*A++;
S=Init_SeqStack();
while(ch!='#')
{
if(IsNum(ch))
Push_SeqStack(S,ch-'0');
else
{
Pop_SeqStack(S,&b);
Pop_SeqStack(S,&a);
switch(ch)
{
case '+': c=(int)a+(int)b;break;
case '-': c=(int)a-(int)b;break;
case '*': c=(int)a*(int)b;break;
case '/': c=(int)a/(int)b;break;
case '%': c=(int)a%(int)b;break;
}
Push_SeqStack(S,c);
}
ch=*A++;
}
GetTop_SeqStack(S,&Result);
Destroy_SeqStack(&S);
return (double)Result;
}
//主函数
main()
{
char A[30];
char B[30];
double result;
printf("请输入一个算术表达式,并以#结束:\n");
scanf("%s",A);
infix_exp_value(A,B);
result=postfix_exp(B);
printf("运算结果是:");
printf("%f",result);
printf("\n");
getch();
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
计算器.zip (2个子文件)
jisuanqi.cpp 3KB
jisuanqi.exe 200KB
共 2 条
- 1
资源评论
- Tony__sama2012-10-31这个真心 不错 运算完美
RysonFeng
- 粉丝: 6
- 资源: 20
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功