Sequence_postfix expression(後綴表達式求值)

#include<stdio.h>
#define MAXSIZE 100


double readnumber(char f[], int *i)//將char類型存儲的數字轉化爲double型
{
double x = 0.0;
int k = 0;
while (f[*i] >= '0'&&f[*i] <= '9')
{
x = x * 10 + (f[*i] - '0');
++(*i);
}
if (f[*i] == '.')
{
++(*i);
while (f[*i] >= '0'&&f[*i] <= '9')
{
x = x * 10 + (f[*i]-'0');
++(*i);
++k;//用k記錄小數點後的位數
}
}
while (k != 0)
{
x = x / 10.0;
k = k - 1;
}
//printf("讀出的數爲:%lf\n", x);
return x;
}


double evalpost(char f[])//求後綴表達式的值
{
double obst[MAXSIZE];//操作數棧,依次存放操作數
int top = 0;
int i = 0;
double x1, x2;
while (f[i] != '#')//結束標誌爲'#'
{
if (f[i] >= '0'&&f[i] <= '9')
{
obst[top] = readnumber(f, &i);
//printf("top=%lf,", obst[top]);
top++;
}
else 
if (f[i] == ' ')
i++;
else
if (f[i] == '+')
{
x2 = obst[--top];
x1 = obst[--top];
// printf("x1=%lf,x2=%lf", x1, x2);
obst[top] = x1 + x2;
//printf("top=%lf,", obst[top]);
++top;
i++;
}
else
if (f[i] == '-')
{
x2 = obst[--top];
x1 = obst[--top];
obst[top] = x1 - x2;
++top;
i++;
}
else
if (f[i] == '*')
{
x2 = obst[--top];
x1 = obst[--top];
obst[top] = x1 * x2;
++top;
i++;
}
else
if (f[i] == '/')
{
x2 = obst[--top];
x1 = obst[--top];
obst[top] = x1 / x2;
++top;
i++;
}
}
return obst[--top];
}


int is_operation(char op)//判斷是否爲運算符
{
switch (op)
{
case '+':
case'-':
case '*':
case '/':return 1;
default:return 0;
}
}


int priority(char op)//返回運算符的優先級
{
switch (op)
{
case '#':return -1;
case '(':return 0;
case '+':
case '-':return 1;
case '*':
case '/':return 2;
default:return -1;
}
}


void postfix(char e[], char f[])//中綴表達式轉後綴表達式
{
int i = 0,j = 0;
char opst[100];
int top, t;
top = 0;
opst[top] = '#';
top++;
while (e[i] != '#')
{
if ((e[i] >='0'&&e[i] <= '9') || e[i] == '.')
{
f[j++] = e[i];
}
else
if (e[i] == '(')//左括號一律進
{
opst[top] = e[i];
++top;
}


else 
if (e[i] == ')')//右括號一律出,直到出棧到左括號
{
while (opst[top-1] != '(')
f[j++] = opst[--top];
--top;
}
else
if (is_operation(e[i]))//正常運算符判斷優先級決定出入棧操作
{
f[j++] = ' ';
while (priority(opst[top - 1]) >= priority(e[i]))
/*只有欲入棧的運算符優先級大於棧頂元素,纔可以入運算符棧,
否則運算符棧頂的運算符出棧參與運算*/
f[j++] = opst[--top];
opst[top] = e[i];
top++;
}
i++;
}
while (top)
f[j++] = opst[--top];
f[j] = '\0';//不加'\0',計算結果不正確
}


void main()
{
char c[MAXSIZE];
char f[MAXSIZE];
char ch;
int i = 0;
while (1)
{
ch = getchar();
if (ch == '#')
{
c[i] = ch;
++i;
break;
}
else {
c[i] = ch;
++i;
}
}
c[i] = '\0';
int j = 0;
printf("輸入的內容是:");
for (; c[j] != '\0'; ++j)
printf("%c", c[j]);
printf("\n");
postfix(c, f);
int k = 0;
printf("後綴表達式爲:");
for (; f[k] != '\0'; ++k)
printf("%c", f[k]);
putchar('\n');
printf("計算結果爲:%lf\n", evalpost(f));
}
發佈了46 篇原創文章 · 獲贊 16 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章