实现计算器功能
http://www.1point3acres.com/bbs/thread-12175-1-1.html
| 如何寫(xiě)出一個(gè)簡(jiǎn)單的4則運(yùn)算的程序。 輸入 " 1 -2*3 + 6/3"? 輸出 -3 只用支持正數(shù)int的,+,-,*,/,不用寫(xiě)出()的情況 |
要注意的問(wèn)題是,空格。。。。
可以直接用逆波蘭式做,稍麻煩,用遞歸可以直接做
int cal(int last, int idx ) {//idx指向當(dāng)前的運(yùn)算符,last指前一個(gè)數(shù)字if (idx >= n)return last;if (vt[idx] == "x")return cal(last * atoi(vt[idx+1].c_str()), idx + 2);if (vt[idx] == "/")return cal(last / atoi(vt[idx+1].c_str()), idx + 2);if (vt[idx] == "+"){if (idx + 2 >=N || vt[idx + 1] == "-" || vt[idx + 1] == "+")return cal(last + atoi(vt[idx+1].c_str()), idx +2);else return last + cal(atoi(vt[idx+1].c_str()), idx +2);}//"-"同理 }
總結(jié)
- 上一篇: Reverse Polish Notat
- 下一篇: c++实现读写共享锁