(有可能只有我的代码会出这个问题)
这是我的代码
#include<iostream>
#include<stack>
#include<unordered_map>
#include<algorithm>
#define int long long
using namespace std;
stack<char> op;
string ans;
string s;
unordered_map<char,int> f;
void priority(){
f['(']=f[')']=0;
f['+']=f['-']=1;
f['*']=f['/']=2;
f['^']=3;
}
void mid_to_la(){
int x=s.size();
ans.push_back(' ');
for(int i=0;i<x;i++){
if(isdigit(s[i])){
ans.push_back(s[i]);
ans.push_back(' ');
continue;
}
if(s[i]=='^'){
op.push(s[i]);
continue;
}
if(s[i]=='('){
op.push(s[i]);
continue;
}
if(s[i]==')'){
while(op.top()!='('){
ans.push_back(op.top());
ans.push_back(' ');
op.pop();
}
op.pop();
continue;
}
while(op.size()&&f[op.top()]>=f[s[i]]){
ans.push_back(op.top());
ans.push_back(' ');
op.pop();
}
op.push(s[i]);
}
while(op.size()){
ans.push_back(op.top());
ans.push_back(' ');
op.pop();
}
return;
}
void print(){
int x=ans.size();
for(int i=1;i<x-1;i++){
cout<<ans[i];
}
cout<<endl;
}
string calc(int a,int b,char ch){
int res=1;
if(ch=='^'){
while(b){
res*=a;
b--;
}
}else if(ch=='+'){
res=a+b;
}else if(ch=='-'){
res=a-b;
}else if(ch=='*'){
res=a*b;
}else if(ch=='/'){
res=a/b;
}
string d="";
bool fl=0;
if(res<0){
res=-res;
fl=1;
}
while(res){
d.push_back(res%10+'0');
res/=10;
}
reverse(d.begin(),d.end());
string ans2="";
if(fl){
ans2.push_back('-');
}
int x=d.size();
for(int i=0;i<x;i++){
ans2.push_back(d[i]);
}
return ans2;
}
bool check(){
int x=ans.size();
for(int i=0;i<x;i++){
if(ans[i]==' '){
continue;
}
if(!isdigit(ans[i])&&!isdigit(ans[i+1])){
return 1;
}
}
return 0;
}
void get_ans(){
while(1){
print();
if(!check()){
break;
}
int x=ans.size();
string ans2=ans;
ans2[x]='+';
ans.clear();
int num1=0,num2=0;
int l=0,r=0;
char ch;
for(int i=0;i<x;i++){
if(ans2[i]==' '){
continue;
}
if(!isdigit(ans2[i])&&!isdigit(ans2[i+1])){
r=i,ch=ans2[i];
break;
}
}
int cnt=0;
for(int i=r-1;~i;i--){
if(ans2[i]==' '){
cnt++;
if(cnt>2){
l=i;
break;
}
continue;
}
}
bool fl=1;
bool fl1=0,fl2=0;
for(int i=l+1;i<r;i++){
if(ans2[i]==' '){
fl=0;
continue;
}
if(fl){
if(ans2[i]=='-'){
fl1=1;
}else{
num1=num1*10+(ans2[i]-'0');
}
}else{
if(ans2[i]=='-'){
fl2=1;
}else{
num2=num2*10+(ans2[i]-'0');
}
}
}
if(fl1){
num1=-num1;
}
if(fl2){
num2=-num2;
}
// cout<<num1<<' '<<num2<<endl;
for(int i=0;i<=l;i++){
ans.push_back(ans2[i]);
}
string ans3=calc(num1,num2,ch);
int y=ans3.size();
for(int i=0;i<y;i++){
ans.push_back(ans3[i]);
}
for(int i=r+1;i<x;i++){
ans.push_back(ans2[i]);
}
}
return;
}
signed main(){
cin>>s;
priority();
mid_to_la();
// cout<<ans;
get_ans();
return 0;
}
hack(非常简单):
2-2
正确输出
2 2 -
0
我的输出:
2 2 -
(我应该没读错题吧)