实现计算器功能
http://www.1point3acres.com/bbs/thread-12175-1-1.html
| 如何寫出一個簡單的4則運算的程序。 輸入 " 1 -2*3 + 6/3"? 輸出 -3 只用支持正數int的,+,-,*,/,不用寫出()的情況 |
要注意的問題是,空格。。。。
可以直接用逆波蘭式做,稍麻煩,用遞歸可以直接做
int cal(int last, int idx ) {//idx指向當前的運算符,last指前一個數字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);}//"-"同理 }
總結
- 上一篇: Reverse Polish Notat
- 下一篇: 原地排列字符串