简易的四则运算

王朝other·作者佚名  2008-06-01
窄屏简体版  字體: |||超大  

这个程序自己写的有些局限,可惜只能对0~9的四则运算起作用,我正在对它进行改进,希望各位能提出好的意见,谢谢!!

#include<stdio.h>

#include<math.h>

#include<stdlib.h>

#include<ctype.h>

#define maxism 15

typedef strUCt stack

{

char stack[maxism];

int top;

}stack;

stack *L;

char after[maxism];

void initialstack(stack *T)

void push(stack *T,int x)

void change()

{

int i=0,j,m=0;

char str[maxism],ch;

printf("please enter the compute eXPression(only contained +,-,*,/,(,),begin and end with '#'): ");

gets(str);

i++;

ch=str[i];

initialstack(L);

while(ch!='#')

{

switch(ch)

{

case'(':

L->top++;

L->stack[L->top]=ch;

break;

case')':

while(L->stack[L->top]!='(')

{

after[m]=L->stack[L->top];

L->top--;

m++;

}

L->top--;

break;

case'+':

case'-':

while(L->top!=0&&L->stack[L->top]!='(')

{

after[m]=L->stack[L->top];

L->top--;

m++;

}

L->top++;

L->stack[L->top]=ch;

break;

case'*':

case'/':

while(L->stack[L->top]=='*'L->stack[L->top]=='/')

{

after[m]=L->stack[L->top];

L->top--;

m++;

}

L->top++;

L->stack[L->top]=ch;

break;

case' ':

break;

default:

if(ch>='0'&&ch<='9')

{

after[m]=ch;

m++;

}

else

{

printf("error! ");

exit(1);

}

}

i++;

ch=str[i];

}

while(L->stack[L->top]!=0)

printf("the changed expression is: ");

for(j=0;j<m;j++)

printf("%c",after[j]);

after[m]='#';

printf("%c",after[m]);

}

void compute(stack *L)

{

int i=0,result,d;

char ch;

initialstack(L);

ch=after[i];

while(ch!='#')

{

while(ch>='0'&&ch<='9')

{

d=ch-'0';

push(L,d);

i++;

ch=after[i];

}

switch(ch)

{

case'+':

L->stack[L->top-1]=L->stack[L->top]+L->stack[L->top-1];

L->top--;

break;

case'-':

L->stack[L->top-1]=L->stack[L->top-1]-L->stack[L->top];

L->top--;

break;

case'*':

L->stack[L->top-1]=L->stack[L->top]*L->stack[L->top-1];

L->top--;

break;

case'/':

if(L->stack[L->top-1]==0)

{

printf("error due to the wrong input format! ");

exit(0);

}

else

L->stack[L->top-1]=L->stack[L->top-1]/L->stack[L->top];

L->top--;

break;

default:

break;

}

i++;

ch=after[i];

}

printf(" the final result is:%d",L->stack[L->top]);

}

main()

{int result;

clrscr();

change();

compute(L);

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航