题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
说实话,当初学的时候还觉得很简单。
结果自己写,写的就一塌糊涂。ε=(´ο`*)))唉
需要注意的几点:
- 数据类型。涉及到“11”这种多位的数字怎么从字符串转换为整数
- 出栈的顺序等。这个可以按算法原理自己用实际的例子推导一遍,尤其是最后的处理,也就是$后面的。
- 最后就是各种小逻辑(我debug了好久呢)
#include<iostream> #include<stdio.h> #include<string> #include<stack> #include<vector> using namespace std; float calculateFunc(float x, float y, char op){ float ans = 0; if(op == '+') ans = y+x; else if(op == '-') ans = x-y; else if(op == '*') ans = x*y; else ans = x*1./y; return ans; } int str2int(string x){ int ans = 0; for(int i=0;i<x.size();++i){ ans = ans*10+x[i]-'0'; } return ans; } int main(){ string s; vector<string> ss; while(cin >> s){ if(s=="0") return 0; ss.push_back(s); while(cin >> s){ ss.push_back(s); if(cin.get()=='\n') break; } ss.push_back("$"); stack<char> sign; stack<float> num; sign.push('#'); for(int i=0;i<ss.size() && !sign.empty();++i){ char c; if(isdigit(ss[i][0])){ num.push(str2int(ss[i])); continue; }else c = ss[i][0]; if(c == '$'){ while(sign.top() != '#'){ char op = sign.top(); float x = num.top(); num.pop(); float y = num.top(); num.pop(); num.push(calculateFunc(y, x, op)); sign.pop(); } printf("%.2f\n", num.top()); sign.pop(); num.pop(); ss.clear(); break; } else{ char op = sign.top(); if(op == '#'){ sign.push(c); }else if(op == '+' || op == '-'){ if(c=='*' || c=='/'){ sign.push(c); }else{ float x = num.top(); num.pop(); float y = num.top(); num.pop(); num.push(calculateFunc(y, x, op)); sign.pop(); sign.push(c); } }else{ float x = num.top(); num.pop(); float y = num.top(); num.pop(); num.push(calculateFunc(y, x, op)); sign.pop(); --i; // sign.push(c); } } } } return 0; }