2022-2
作者:
许鑫蓁
,
2025-03-08 20:46:07
· 江西
,
所有人可见
,
阅读 2
2022-2
1)核心处理即用栈去模拟表达式求值问题,很多细节你没有写好(比如在处理数字,处理括号上)
2)输入时因为直接cin输入整数,就继续下一行的getline,导致多读入一个换行符,导致卡了好久,输入输出的问题是非常重要的问题,要仔细
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
#include <unordered_map>
#include <cctype>
using namespace std;
double val[26];
stack<char> a;
stack<double> b;
void eval()
{
double y = b.top(); b.pop();
double x = b.top(); b.pop();
char c = a.top(); a.pop();
if(c == '+') b.push(x + y);
else if(c == '-') b.push(x - y);
else if(c == '/') b.push(x / y);
else b.push(x * y);
}
int main()
{
string s;
while(getline(cin, s))
{
if(s == "Exit") break;
else if(s[1] != '=' && s[0]== 'r')
{
for(int i = 5; i < s.size(); i ++)
{
if(s[i] != ' ')
{
double num;
cin >> num;
val[s[i] - 'a'] = num;
}
}
cin.ignore();//忽略后面的换行符
}
else if(s[0] == 'p' && s[1] != '=')
{
for(int i = 6; i < s.size(); i ++)
{
if(s[i] != ' ') printf("%.2lf ", val[s[i] - 'a']);
}
cout << endl;
}
else
{
unordered_map<char, int> pre = {{'+', 1}, {'-', 1}, {'/', 2}, {'*', 2}};
for(int i = 2; i < s.size(); i ++)
{
if(isdigit(s[i]))
{
int x = 0, j = i;
while(j < s.size() && isdigit(s[j])) x = x * 10 + s[j ++] - '0';
i = j - 1;
b.push(x);
}
else if(s[i] == '(') a.push(s[i]);
else if(s[i] == ')')
{
while(a.top() != '(') eval();
a.pop();
}
else if(isalpha(s[i])) b.push(val[s[i] - 'a']);
else
{
while(a.size() && pre[s[i]] <= pre[a.top()]) eval();
a.push(s[i]);
}
}
while(a.size()) eval();
val[s[0] - 'a'] = b.top();
b.pop();
}
}
return 0;
}
逻辑写的太冗余,太复杂,就容易出错,要多用字符串切割substr()函数
在判断的时候可以直接
else if(s.substr(0, 4) == "read")
else if(s.substr(0, 5) == "print")
样例:
read a
10
b=20
c=(a+b)/4
m=(a-c)*(a+b)
print a b c m
Exit
输出:
10.00 20.00 7.50 75.00