这是某本书上的题,书上给的代码有bug
代码:
//草,树上给的代码有bug
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top,S[1000];
void push(int x)
{
S[++top]=x;
}
int pop()
{
top--;
return S[top+1];
}
int main()
{
int a,b;
top=0;
char s[100];
while(scanf("%s",s)!=EOF) { // 这不能用EOF,因为他会一直输入下去
if( s[0]=='+') {
a=pop();
b=pop();
push(a+b);
} else if(s[0]=='-') {
b=pop();
a=pop();
push(a-b);
} else if(s[0]=='*') {
a=pop();
b=pop();
push(a*b);
} else {
push(atoi(s));
}
}
printf("%d\n",pop());
return 0;
}
改过的代码:
//草,这题有bug
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top,S[1000];
void push(int x)
{
S[++top] = x;
}
int pop()
{
top--;
return S[top+1];
}
int main()
{
int a,b;
top=0;
char s[100];
while(scanf("%s", s),s[0]!='m') { //s[0]!='m',m是输入的结束标志防止上述股情况发生
if( s[0] == '+') {
a=pop();
b=pop();
push(a + b);
} else if(s[0] == '-') {
b=pop();
a=pop();
push(a - b);
} else if(s[0] == '*') {
a=pop();
b=pop();
push(a * b);
} else {
push(atoi(s));
}
}
printf("%d\n", pop());
return 0;
}
// 输入:
// 1 2 + 3 4 - *
自己写的代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
int a,b;
stack<int > sta;
char s[100];
while(scanf("%s", s)!=EOF) {
if( s[0] == '+') {
a=sta.top();
sta.pop();
b=sta.top();
sta.pop();
sta.push(a + b);
} else if(s[0] == '-') {
b=sta.top();
sta.pop();
a=sta.top();
sta.pop();
sta.push(a - b);
} else if(s[0] == '*') {
a=sta.top();
sta.pop();
b=sta.top();
sta.pop();
sta.push(a * b);
} else {
sta.push(atoi(s));
}
printf("%d\n", sta.top());
}
printf("%d\n", sta.top());
return 0;
}
// 1 2 + 3 4 - *