當前位置:編程學習大全網 - 編程語言 - 用c語言棧計算順序表達式

用c語言棧計算順序表達式

#include <stdio.h>

double readnumber(char a[],int *i)//將數字字符轉變成相應的數

{

double x=0.0;

int k=0;

while(a[*i]>='0'&&a[*i]<='9')

{

x=x*10+a[*i]-'0';

(*i)++;

}

if(a[*i]=='.')

{

(*i)++;

while(a[*i]>='0'&&a[*i]<='9')

{

x=x*10+a[*i]-'0';

(*i)++;

k++;

}

}

while(k!=0)

{

x=x/10.0;

k=k-1;

}

return x;

}

double yunsuan(char a[])//求壹個後綴表達式的值

{

double obst[100],b,c;//操作數棧

int top=0,i=0;

while(a[i]!='\0')

{

if(a[i]>='0'&&a[i]<='9')

obst[top++]=readnumber(a,&i);

else if(a[i]==' ') i++;

else if(a[i]=='+')

{

b=obst[--top];

c=obst[--top];

obst[top++]=b+c;

i++;

}

else if(a[i]=='-')

{

b=obst[--top];

c=obst[--top];

obst[top++]=c-b;

i++;

}

else if(a[i]=='*')

{

b=obst[--top];

c=obst[--top];

obst[top++]=b*c;

i++;

}

else if(a[i]=='/')

{

b=obst[--top];

c=obst[--top];

obst[top++]=c/b;

i++;

}

}

return obst[0];

}

int pd(char op)//判斷壹個字符是不是運算符

{

switch(op)

{

case '+':

case '-':

case '*':

case '/':return 1;

default :return 0;

}

}

int priority(char op)//求運算符的優先級

{

switch(op)

{

case '\0':return -1;

case '(':return 0;

case '+':

case '-':return 1;

case '*':

case '/':return 2;

default:return -1;

}

}

void charge(char a[],char b[])//將中綴表達式轉換等價的後綴表達式

{

int i=0,j=0;

char opst[100];

int top,t;

top=0;

opst[top]='\0';

top++;

while(a[i]!='\0')

{

if(a[i]>='0'&&a[i]<='9'||a[i]=='.')

b[j++]=a[i];//遇到數字和小數點直接寫入後綴表達式

else if(a[i]=='(')//遇到左括號進入操作符棧

{

opst[top]=a[i];

top++;

}

else if(a[i]==')')

{

t=top-1;

while(opst[t]!='(')

{//'('之前出棧

b[j++]=opst[--top];

t=top-1;

}

top--;

}

else if(pd(a[i]))//'+','-','*','/'

{

b[j++]=' ';//用空格分開兩個操作數

while(priority(opst[top-1])>=priority(a[i]))

b[j++]=opst[--top];

opst[top]=a[i];

top++;

}

i++;

}

while(top) b[j++]=opst[--top];

}

int main()

{

char a[100],b[100];

double jieguo;

printf("\n\t請輸入算術表達式:");

scanf("%s",a);

charge(a,b);

jieguo=yunsuan(b);

printf("\t表達式運算的結果為:%lf",jieguo);

return 0;

}

  • 上一篇:統計學專業就業前景如何?理科男生專業方向該如何選擇?
  • 下一篇:網絡編程的四層模型包括
  • copyright 2024編程學習大全網