2016/9/29 1002. 简单计算器

来源:互联网 发布:调节电脑屏幕亮度软件 编辑:程序博客网 时间:2024/06/06 04:25

首先要说的是题目里的“忽略空格!”和要考虑有小数点的情况,之前没搞清楚被坑了好久。

然后就是计算器的实现方法,就是用理论课上讲的对一个字符串,首先对数字压入数字栈,如果是运算符,则根据一个表定义的大小:(直接拍了书上的笔记了)


若是栈顶符号>当前检查到的符号,则弹出两个数和一个运算符进行计算,并将结果压入栈,直到进入其他情况。

若是<,则简单的将检查的符号压入即可。

另外,当到字符串最后时,则不断运算直到符号栈空,此时输出结果。

#include <iostream>#include <stack>#include <string>#include <iomanip>#include <cmath>using namespace std;bool isNumber(char a){if ((a <= '9'&&a >= '0')){return true;}else return false;}bool isCal(char a){if (a == '+' || a == '-' || a == '*' || a == '/'){return true;}else return false;}int main(){int t;cin >> t;cin.ignore();while (t--){string s;getline(cin,s);stack<double> number;stack<char> cal;double temp = 0;double temp_ = 0;int digitCount = 0;bool digit = false;for (int i = 0; i <= s.length() - 1; i++){if (s[i] == '.'){digit = true;continue;}if (s[i] == ' '){continue;}if (isNumber(s[i])){if (!digit){temp = temp * 10 + s[i] - 48;}else{digitCount++;temp_ = temp_ + (s[i] - 48)*pow(10, 0-digitCount);}}else{number.push(temp+temp_);temp = 0;temp_ = 0;digitCount = 0;digit = false;}if (isCal(s[i])){while (!cal.empty()){if ((cal.top() == '+' || cal.top() == '-') && (s[i] == '*' || s[i] == '/')) //1<2{break;}else // 1>2{double a = number.top();number.pop();double b = number.top();number.pop();if (cal.top() == '*'){number.push(a*b);}else if (cal.top() == '/'){number.push(b / a);}else if (cal.top() == '+'){number.push(b + a);}else if (cal.top() == '-'){number.push(b - a);}cal.pop();}}cal.push(s[i]);}if (i == s.length() - 1){number.push(temp + temp_);temp = 0;temp_ = 0;digitCount = 0;digit = false;while (!cal.empty()){double a = number.top();number.pop();double b = number.top();number.pop();if (cal.top() == '*'){number.push(a*b);}else if (cal.top() == '/'){number.push(b / a);}else if (cal.top() == '+'){number.push(b + a);}else if (cal.top() == '-'){number.push(b - a);}cal.pop();}}}cout << setiosflags(ios::fixed) << setprecision(3) << number.top() << endl;}}


0 0
原创粉丝点击