这道题本身没什么,就是两个栈计算表达式,但我一直re,原来是输入之间有空行导致的,,,,,吸取教训
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#define MAX 2000010
using namespace std;
char s[MAX];
long long cal(long long a,long long b,char opt){
if(opt=='+')
return a+b;
if(opt=='-')
return a-b;
if(opt=='*')
return a*b;
if(opt=='/')
return a/b;
}
int main(){
int n,len,start,flag;
char ch;
cin>>n;
getchar();
while(n--){
len=0;
while(1){
ch=getchar();
if(ch=='\n')
break;
else
if(ch>='0'&&ch<='9'||ch=='+'||ch=='-'||ch=='*'||ch=='/'){
s[len++]=ch;
}
}
if(len==0){
n++;
continue;
}
stack<long long>num;
stack<char>opt;
if(s[0]=='+'||s[0]=='-'){
start=1;
if(s[0]=='-')
flag=1;
else
flag=0;
}
else{
flag=0;
start=0;
}
for(int i=start;i<len;i++){
if(s[i]>='0'&&s[i]<='9'){
long long number=s[i]-'0';
int j;
for(j=i+1;j<len&&s[j]>='0'&&s[j]<='9';j++)
number=number*10+s[j]-'0';
i=j-1;
if(flag){
number=-number;
flag=0;
}
num.push(number);
}
else if(s[i]=='*'||s[i]=='/'){
while(!opt.empty()&&(opt.top()=='*'||opt.top()=='/')){
long long b=num.top();
num.pop();
long long a=num.top();
num.pop();
char optr=opt.top();
opt.pop();
num.push(cal(a,b,optr));
}
opt.push(s[i]);
}
else if(s[i]=='+'||s[i]=='-'){
while(!opt.empty()){
long long b=num.top();
num.pop();
long long a=num.top();
num.pop();
char optr=opt.top();
opt.pop();
num.push(cal(a,b,optr));
}
opt.push(s[i]);
}
}
while(!opt.empty()){
long long b=num.top();
num.pop();
long long a=num.top();
num.pop();
char optr=opt.top();
opt.pop();
num.push(cal(a,b,optr));
}
cout<<num.top()<<endl;
}
return 0;
}