代码如下、 其他完全一致,仅仅读入修改 正确(cin)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
stack<char> st;
string a;
int ans[3],f=1,ff=1;
char ansx;
void add(){
char x;
x=st.top(); st.pop();
if(x>='a' && x<='z'){
ansx=x;
f=1;
x=st.top(); st.pop();
if(x=='+'){
ans[f]=ans[f]+1*ff;
return ;
}
else if(x=='-') {
ans[f]=ans[f]-1*ff;
return ;
}
}
else f=2;
int tt=0;
string t;
while(x!='-' && x!='+'){
t=x+t;
x=st.top(); st.pop();
}
for(int i=0;i<=t.length()-1;i++)
tt=tt*10+(int)(t[i]-'0');
if(x=='-') ans[f]=ans[f]-tt*ff;
else ans[f]=ans[f]+tt*ff;
return ;
}
int main(){
cin>>a;
if(a[0]!='-') a='+'+a;
int t=a.find("=");
if(a[t+1]!='-') a.insert(t+1,"+");
st.push(a[0]);
for(int i=1;i<=a.length()-1;i++){
if(a[i]=='='){
add();
st.push(a[i+1]);
i++,ff=-1; continue;
}
if(a[i]=='+' || a[i]=='-')
add();
st.push(a[i]);
}add();
// cout<<ans[1]<<endl<<ans[2];
double anss= (double)(ans[2]*(-1))/(double)(ans[1]);
if(anss==-0)anss=0;
printf("%c=%.3f",ansx,anss);
}
错误的 getline
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
stack<char> st;
string a;
int ans[3],f=1,ff=1;
char ansx;
void add(){
char x;
x=st.top(); st.pop();
if(x>='a' && x<='z'){
ansx=x;
f=1;
x=st.top(); st.pop();
if(x=='+'){
ans[f]=ans[f]+1*ff;
return ;
}
else if(x=='-') {
ans[f]=ans[f]-1*ff;
return ;
}
}
else f=2;
int tt=0;
string t;
while(x!='-' && x!='+'){
t=x+t;
x=st.top(); st.pop();
}
for(int i=0;i<=t.length()-1;i++)
tt=tt*10+(int)(t[i]-'0');
if(x=='-') ans[f]=ans[f]-tt*ff;
else ans[f]=ans[f]+tt*ff;
return ;
}
int main(){
getline(cin,a);
if(a[0]!='-') a='+'+a;
int t=a.find("=");
if(a[t+1]!='-') a.insert(t+1,"+");
st.push(a[0]);
for(int i=1;i<=a.length()-1;i++){
if(a[i]=='='){
add();
st.push(a[i+1]);
i++,ff=-1; continue;
}
if(a[i]=='+' || a[i]=='-')
add();
st.push(a[i]);
}add();
// cout<<ans[1]<<endl<<ans[2];
double anss= (double)(ans[2]*(-1))/(double)(ans[1]);
if(anss==-0)anss=0;
printf("%c=%.3f",ansx,anss);
}