wangzaixi @ 2024-08-07 22:22:18
#include<bits/stdc++.h>
using namespace std;
stack <int> s1;
int main(){
char a;
int b,x,y;
while(a!='@'){
b=((int)a)-48;
if(a>='0'&&a<='9'){
s1.push(b);
}
else if(a=='+'){
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
s1.push(x+y);
}
else if(a=='-'){
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
s1.push(x-y);
}
else if(a=='*'){
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
s1.push(x*y);
}
else if(a=='/'){
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
s1.push(x/y);
}
}
cout<<s1.top();
return 0;
}
by haimingbei @ 2024-08-09 14:15:30
@wangzaixi 相当于你只输入了一个字符……
by wangzaixi @ 2024-08-09 14:19:14
@haimingbei RE+WA了
#include<bits/stdc++.h>
using namespace std;
stack <int> s1;
char a;
int b,x,y;
int main(){
cin>>a;
while(a!='@'){
b=((int)a)-48;
if(a>='0'&&a<='9'){
s1.push(b);
}
else{
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
if(a=='+'){
s1.push(x+y);
}
else if(a=='-'){
s1.push(x-y);
}
else if(a=='*'){
s1.push(x*y);
}
else if(a=='/'){
s1.push(x/y);
}
}
cin>>a;
}
cout<<s1.top();
return 0;
}
by haimingbei @ 2024-08-09 14:19:21
还有,你第9行b是啥意思?题目不是说遇到“.”才算一个数结束吗?要是那个数是两位数呢?所以我求n直到有‘.’才算一个数算了出来,然后n还要清零,你也没清零
by haimingbei @ 2024-08-09 14:30:10
第9行b=((int)a)-48;
改为if(a>='0' && a<='9') b=b*10+a-48;
by haimingbei @ 2024-08-09 14:31:00
@wangzaixi 第10行if(a>='0'&&a<='9')
改为else if(a=='.')
by wangzaixi @ 2024-08-09 14:31:45
@haimingbei 就一个AC
{
char a;
int b=0;
cin>>a;
while(a!='@'){
if(a>='0'&&a<='9'){
b=b*10+a-'0';
}
else if(a=='.'){
s1.push(b);
b=0;
}
else{
int x,y,z;
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
if(a=='+'){
z=x+y;
}
else if(a=='-'){
z=x-y;
}
else if(a=='*'){
z=x*y;
}
else if(a=='/'){
z=x/y;
}
s1.push(z);
}
cin>>a;
}
cout<<s1.top();
return 0;
}
by haimingbei @ 2024-08-09 14:32:30
@wangzaixi 遇到“.”才算一个数,所以b算好存入栈后还要清零
第11行和12行之间加上b=0
by wangzaixi @ 2024-08-09 14:33:18
@haimingbei 写b=0了呀
by haimingbei @ 2024-08-09 14:36:22
@wangzaixi 栈是先进后出,所以你不是第一个弹得数是x,第二个是y,但我们应该从左往右算,你x-y
要改成y-x
,除法也是(加法和乘法正反都一样,所以不用改),不然顺序错了,你存进去2-1,1先出来,2后出来,你这样算就是1-2了,所以要y-x和t/x
by haimingbei @ 2024-08-09 14:38:39
@wangzaixi 全部按你代码改好,AC(已包含上述所有讲的点,你自己看看)
#include<bits/stdc++.h>
using namespace std;
stack <int> s1;
char a;
int b,x,y;
int main()
{
char a;
int b=0;
cin>>a;
while(a!='@'){
if(a>='0'&&a<='9'){
b=b*10+a-'0';
}
else if(a=='.'){
s1.push(b);
b=0;
}
else{
int x,y,z;
x=s1.top();
s1.pop();
y=s1.top();
s1.pop();
if(a=='+'){
z=x+y;
}
else if(a=='-'){
z=y-x;
}
else if(a=='*'){
z=x*y;
}
else if(a=='/'){
z=y/x;
}
s1.push(z);
}
cin>>a;
}
cout<<s1.top();
return 0;
}