题目:输入行数,再在每行输入一个表达式,得出结果。
输入示例:
3
1+1
2.2/3
1+2*3
输出示例:
2
0.7
7
代码:
#include <iostream>
#include <stack>
#include <sstream>
#include <cctype>
using namespace std;
bool isNumber(char c) {
if (isdigit(c) || c == '.') return true;
else return false;
}
bool isOperater(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') return true;
else return false;
}
bool isHighLevel(char newOp, char oldOp) {
if ((newOp == '*' || newOp == '/')
&& (oldOp == '+' || oldOp == '-' || oldOp == '#'))
return true;
else return false;
}
double opNumber(double a, double b, char op) {
if (op == '+') return a + b;
else if (op == '-') return a - b;
else if (op == '*') return a * b;
else if (op == '/') return a / b;
}
int main()
{
int n;
cin >> n;
cin.get();
for (int i = 0; i < n; ++i) {
string str;
getline(cin, str);
str += "#";
stack<char> sta;
sta.push('#');
int strLen = str.length();
string hstr = "";
for (int j = 0; j < strLen; ++j) {
if (isNumber(str[j])) hstr += str[j];
else if (isOperater(str[j])) {
hstr += "|";
if (isHighLevel(str[j], sta.top())) {
sta.push(str[j]);
}
else if (sta.top() == '#') {
sta.push(str[j]);
}
else {
hstr += sta.top();
sta.pop();
sta.push(str[j]);
}
}
else if (str[j] == '#') {
hstr += '|';
while (!sta.empty() && sta.top() != '#') {
hstr += sta.top();
sta.pop();
}
break;
}
}
stack<double> staNumber;
staNumber.push(0);
int hstrLen = hstr.length();
stringstream ss;
for (int j = 0; j < hstrLen; ++j) {
if (isNumber(hstr[j])) {
ss << hstr[j];
}
else if (hstr[j] == '|') {
double temp;
ss >> temp;
staNumber.push(temp);
ss.clear();
}
else if (isOperater(hstr[j])) {
double a = staNumber.top();
staNumber.pop();
double b = staNumber.top();
staNumber.pop();
double c = opNumber(b, a, hstr[j]);
staNumber.push(c);
}
}
double fin = staNumber.top();
cout << fin << endl;
}
return 0;
}