标签:inf turn 结果 src i++ remove float == scanf
坑了老子半天,结果是 float 范围不够!!!
基本思想:
将当前符号与栈顶符号进行对比,如果当前符号优先级小于栈顶符号,数字栈弹出两个数进行栈顶符号运算,继续和当前栈顶符号比较,直到当前符号优先级大于栈顶符号,再将当前元素入栈。
符号栈初始放置一个‘#’,并规定 ‘#’,优先级低于任何符号。
表达式求值是老问题了,但是之前做的也不太完善,很多小地方还是没注意到,WA了好几次。 1. 终止条件,if (s.length() == 1 && s[0] == ‘0‘) break; 否则0+1,类似的就不会计算了。
2. 题目只说了小数,真是没想到中间运算float范围还会超
写的很乱,一直不知道哪里错了,还把别人AC代码拿来做了个对数器,也没发现自己哪儿错了,改来改去,先这样放着吧,过两天再精简下。
完整代码:
#include<stdio.h> #include <string> #include <algorithm> #include <iostream> #include <stack> using namespace std; double operation(double x, char c, double y) { switch (c) { case ‘+‘: return x + y; case ‘-‘: return x - y; case ‘*‘: return x * y; case ‘/‘: return x / y; } } int judge(char stackTop, char now) { switch (now) { case ‘+‘: case ‘-‘: if (stackTop == ‘#‘) return 0; return 1; break; case ‘*‘: case ‘/‘: if (stackTop == ‘#‘ || stackTop == ‘+‘ || stackTop == ‘-‘) return 0; return 1; break; } } int main() { stack<char>symbol; stack<double>num; symbol.push(‘#‘); string s; while (getline(cin, s)) { if (s.length() == 1 && s[0] == ‘0‘) break; s.erase(remove(s.begin(), s.end(), ‘ ‘), s.end()); for (int i = 0; i < s.length(); i++) { int t = 0; if (s[i] >= ‘0‘&&s[i] <= ‘9‘) { while (s[i] >= ‘0‘&&s[i] <= ‘9‘) { t = t*10+(s[i]-‘0‘); i++; } num.push(t); } if (i >= s.length())break; while (judge(symbol.top(), s[i])) { char c = symbol.top(); symbol.pop(); double y = num.top(); num.pop(); double x = num.top(); num.pop(); num.push(operation(x, c, y)); } symbol.push(s[i]); } while (symbol.top() != ‘#‘) { char c = symbol.top(); symbol.pop(); double y = num.top(); num.pop(); double x = num.top(); num.pop(); num.push(operation(x, c, y)); } printf("%.2lf\n", num.top()); num.pop(); } return 0; }
重新精简了一下代码:
#include <stdio.h> #include <string> #include <algorithm> #include <stack> using namespace std; stack<char>symbol; stack<double>num; double operation(char c) { double y = num.top(); num.pop(); double x = num.top(); num.pop(); switch (c) { case ‘+‘: return x + y; case ‘-‘: return x - y; case ‘*‘: return x * y; case ‘/‘: return x / y; } } int judge(char stackTop, char now) { switch (now) { case ‘+‘: case ‘-‘: if (stackTop == ‘#‘) return 0; return 1; break; case ‘*‘: case ‘/‘: if (stackTop == ‘#‘ || stackTop == ‘+‘ || stackTop == ‘-‘) return 0; return 1; break; } } int main() { symbol.push(‘#‘); string s; int d,t; while (scanf("%d",&d)) { char c = getchar(); if (d == 0 && c == ‘\n‘) break; num.push(d); while (scanf("%c %d", &c, &t)) { while (judge(symbol.top(), c)) { num.push(operation(symbol.top())); symbol.pop(); } num.push(t); symbol.push(c); if ((c = getchar() == ‘\n‘)) break; } while (symbol.top() != ‘#‘) { num.push(operation(symbol.top())); symbol.pop(); } printf("%.2lf\n", num.top()); num.pop(); } return 0; }
标签:inf turn 结果 src i++ remove float == scanf
原文地址:https://www.cnblogs.com/czc1999/p/10351970.html