http://www.zhihu.com/question/28049221
这里有个问题说:
能用c语言编写一个简单的计算器,包含加减乘以及括号之间的优先级关系,这样的编程能力算是什么程度?
我也很好奇,能写出来到底怎么样。我写出的代码到底怎么样。便有了下面的代码。
毕竟是好久没有写这些小程序了。
#include <iostream> #include <stack> #include <map> using namespace std; //get a number from a string["123nc14"==>123] bool getNumber(char* input,int& number,int& strMoveOffset) { strMoveOffset = 0; while(input[strMoveOffset]>=48 &&input[strMoveOffset]<58)//this char is a number { strMoveOffset++; } if(!strMoveOffset)//this char is a operator { return false; } //parse the number number = atoi(input); return true; }; int main(int argc,char** argv) { //string for input char input[256]; //number stack and operator stack stack<int> NumStack; stack<char> OperatorStack; //hashtable for operators' priority map<char,int> operatorPriority; operatorPriority['+']=1; operatorPriority['-']=1; operatorPriority['*']=2; operatorPriority['/']=2; operatorPriority['(']=3; operatorPriority[')']=0; operatorPriority['