生活随笔
收集整理的這篇文章主要介紹了
HDU1237 简单计算器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://acm.hdu.edu.cn/showproblem.php?pid=1237
題解:??對于中綴表達式的運算一般要轉化成后綴表達式再作運算,開兩個棧,一個作為操作數棧StackDigital,一個作為操作符棧StackOperator。
1.定義一個函數判定優先級:# 的優先級最低,為0,+ 和 - 的級別相同且高于 #,標為1,* 和 / 的級別相同且高于 + 和 - ,標志為2,
2.先往運算符棧放入一個 # (標定界限),表達式最后也加一個 #(?(標定界限)),
3.遍歷表達式,若讀到數字,則以數字類型輸入,直接放到操作數棧,若讀到的是運算符,則比較讀到的運算符與運算符棧頂符號的級別,
若比棧頂的高,則入棧,否則,從數棧取兩個操作數根據操作符棧頂的操作進行運算,再把結果壓入數棧,剛剛讀到的運算符再與現在運算符棧
頂元素的級別進行比較……最后數剩下的一個元素,就是結果。
?
#include <iostream>
#include <cstdio>
#include <string.h>
#include <ctype.h>
using namespace std;double stDit[300];
char stOp[300],str[300];
int top1,top2;int Priority(char op)
{if (op=='#') return 0;if (op=='+' || op=='-') return 1;if (op=='*' || op=='/')return 2;elsereturn -1;
}
double Operate(double x,double y,char op)
{if (op=='+') return x+y;if (op=='-') return x-y;if (op=='*') return x*y;if (op=='/') return x/y;else return -1;
}double Calc()
{double x,y,tmp;char op;int i,n = strlen(str);top1 = top2 = -1;stOp[++top2] = '#';str[n++] = '#';for(i=0; i < n; ++i){if (str[i]==' ')continue;if (isdigit(str[i])) //是數字{sscanf(str+i,"%lf",&tmp);stDit[++top1] = tmp; //stack pushwhile(isdigit(str[i+1])) //+1很重要++i;}else //是操作符{while (Priority(stOp[top2]) >= Priority(str[i]))//如果操作棧頂的操作符優先級高,則作+-*/運算{if (str[i]=='#' && stOp[top2]=='#')return stDit[top1];y = stDit[top1--];x = stDit[top1--];op = stOp[top2--];stDit[++top1] = Operate(x,y,op);}stOp[++top2] = str[i]; //如果新操作符優先級高,str[i]進棧}}return stDit[top1];
}
int main()
{int i;while (gets(str) != NULL && strcmp(str,"0")!=0){printf("%.2lf\n",Calc());}return 0;
}
?
總結
以上是生活随笔為你收集整理的HDU1237 简单计算器的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。