1.簡單計算器
題目描述
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
輸入
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
輸出
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
樣例輸入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
樣例輸出
12178.21
步驟:
- 1.中綴表達式轉後綴表達式
- 2.計算後綴表達式
#include<cstdio>
#include<iostream>
#include<stack>
#include<queue>
#include<map>
#include<string>
using namespace std;
struct node{
double num; //操作數
char op; //操作符
bool flag;//true代表操作數,flase代表操作符
};
string str;
stack<node> s;//操作符棧
queue<node> q; //後綴表達式序列
map<char,int> op;//操作符優先級映射
//將中綴表達式轉換爲後綴表達式
void change(){
double num;
node temp;
for(int i=0;i<str.length();){
//如果是數字
if(str[i]>='0'&&str[i]<='9'){
temp.flag=true; //標記爲數字
temp.num=str[i]-'0'; //記錄這個操作數的第一個位數
i++;
while(str[i]>='0'&&str[i]<='9'&&i<str.length()){
temp.num=temp.num*10+(str[i]-'0'); //更新這個操作數
i++;
}
q.push(temp); //將數字壓入隊列
}else{ //如果是操作符
temp.flag=false; //標記操作符
//只要操作符棧的棧頂元素比操作符優先級高
//就把操作符站棧頂元素彈出到後綴表達式隊列中
while(!s.empty()&&op[str[i]]<=op[s.top().op]){
q.push(s.top());
s.pop();
}
temp.op=str[i];
s.push(temp);
i++;
}
}
//如果操作數中還有操作符,就把他彈出到後綴表達附中
while(!s.empty()){
q.push(s.top());
s.pop();
}
}
//計算後綴表達式
double Cal(){
double temp1,temp2;
node cui,temp;
while(!q.empty()){
cui=q.front(); //記錄隊首元素
q.pop();
if(cui.flag==true){ //操作數直接壓入棧
s.push(cui);
}else{
//如果是操作符則將棧頂兩個元素彈出,進行對應的運算後將結果壓入棧中
temp2=s.top().num;
s.pop();
temp1=s.top().num;
s.pop();
if(cui.op=='+')
temp.num=temp1+temp2;
else if(cui.op=='-')
temp.num=temp1-temp2;
else if(cui.op=='*')
temp.num=temp1*temp2;
else{
temp.num=temp1/temp2;
}
temp.flag=true;
s.push(temp);
}
}
return s.top().num; //棧頂元素就是後綴表達式的值
}
int main(){
op['+']=op['-']=1; //設定操作數的優先級
op['*']=op['/']=2;
while(getline(cin,str),str!="0"){
//把表達式中的空格去掉
for(string::iterator it =str.end();it!=str.begin();it--){
if(*it == ' '){
str.erase(it);
}
}
//初始化棧
while(!s.empty()){
s.pop();
}
//將中綴表達式轉化爲後綴表達式
change();
//計算後綴表達式
printf("%.2f\n",Cal());
}
return 0;
}
2.括號匹配
題目描述
請寫一個程序,判斷給定表達式中的括號是否匹配,表達式中的合法括號爲”(“, “)”, “[", "]“, “{“, ”}”,這三個括號可以按照任意的次序嵌套使用。
輸入
有多個表達式,輸入數據的第一行是表達式的數目,每個表達式佔一行。
輸出
對每個表達式,若其中的括號是匹配的,則輸出”yes”,否則輸出”no”。
樣例輸入
4 [(d+f)*{}] [(2+3)) ()} [4(6]7)9
樣例輸出
yes no no no
#include<cstdio>
#include<stack>
#include<iostream>
#include<string>
using namespace std;
const int ma=100;
stack <char>s;
int main(){
int n;
scanf("%d",&n);
while(n--){
string str;
cin>>str;
while(!s.empty()){
s.pop();
}
bool flag=true;
for(int i=0;i<str.length();i++){
if(str[i]=='('||str[i]=='{'||str[i]=='['){
s.push(str[i]);
}
else if(str[i]==')'){
if(!s.empty() && s.top()=='(')
{
s.pop();//匹配則彈出
}
else
{
flag=false;
break;
}
}
else if(str[i]=='}'){
if(!s.empty() && s.top()=='{'){
s.pop();//匹配則彈出
}
else{
flag=false;
break;
}
}
else if(str[i]==']'){
if(!s.empty()&&s.top()=='['){
s.pop();
}else{
flag=false;
break;
}
}
}
if(flag){
printf("yes\n");
}else{
printf("no\n");
}
}
}