题目描述
第一行输入行数n,再在接下来n行每行输入一个表达式,得出结果
输入样例
3
1+1
2.2/3
1+2*3
输出样例
2
0.7
7
方法一
#include <bits/stdc++.h>
using namespace std;
double F(string s) {
queue<double> q_num1;
queue<double> q_num2;
queue<char> q_op1;
queue<char> q_op2;
int len = s.size();
string num = "";
double left, right;
char op;
bool flag = false; //用于标注是否是'-'
for (int i = 0; i < len; i++) {
if (i == 0 && s[i] == '-') {
flag = true;
}
if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
if (flag) {
flag = false;
q_num1.push(-atof(num.c_str()));
q_op1.push(s[i]);
}
q_num1.push(atof(num.c_str()));
q_op1.push(s[i]);
num = "";
} else {
num += s[i];
}
}
q_num1.push(atof(num.c_str()));
left = q_num1.front();
q_num1.pop();
while (q_op1.size() != 0) {
right = q_num1.front();
q_num1.pop();
op = q_op1.front();
q_op1.pop();
if (op == '+' || op == '-') {
q_num2.push(left);
left = right;
q_op2.push(op);
} else if(op == '*') {
left = left * right;
} else {
left = left / right;
}
}
q_num2.push(left);
left = q_num2.front();
q_num2.pop();
while (q_op2.size() != 0) {
op = q_op2.front();
q_op2.pop();
right = q_num2.front();
q_num2.pop();
if (op == '+') {
left = left + right;
} else {
left = left - right;
}
}
return left;
}
int main() {
int n;
string s;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
cout << F(s) << endl;
}
return 0;
}
方法二
#include <iostream>
#include <string>
#include <stdlib.h>
#include <queue>
using namespace std;
int main() {
int n;
cin >> n;
string temp;
double left, right;
char op;
string s;
double res;
bool flag; //标识是否是乘除运算,如果是乘除运算则为true
queue<double> q;
for (int i = 0; i < n; i++) {
cin >> s;
temp = "";
while (!q.empty()) {
q.pop();
}
flag = false;
for (int j = 0; j < s.length(); j++) {
if (s[j] == '+' || s[j] == '-' || s[j] == '*' || s[j] == '/') {
if (flag) {
right = atof(temp.c_str());
left = (op == '*' ? left*right : left/right);
flag = false;
} else {
left = atof(temp.c_str());
}
temp = "";
if (s[j] == '+') {
q.push(left);
} else if (s[j] == '-') {
temp += '-';
q.push(left);
} else {
op = s[j];
flag = true;
}
} else {
temp += s[j];
}
}
if (flag) {
right = atof(temp.c_str());
left = (op == '*' ? left*right : left/right);
} else {
left = atof(temp.c_str());
}
q.push(left);
res = 0;
while (!q.empty()) {
double a = q.front();
res += a;
q.pop();
}
cout << res << endl;
}
return 0;
}