栈 ALDS1_3_A:Stack

本文针对书中提供的计算器程序代码存在的bug进行了修复,并进一步优化了代码结构。通过对比原始代码和修改后的代码,详细介绍了每处改动的目的及效果。此外,还提供了一种使用标准模板库(stack)实现的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




这是某本书上的题,书上给的代码有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 - *












                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值