栈的使用(1)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
这道题一开始有点迷,毕竟还有算数优先级的问题,但是用栈解决就很简单了:
先说一下,栈,和数组差不多的一个储存容器,只不过他的数据存储方式是先进后出:
例如输入1,2,3,那么它的输出只能是3,2,1;
例如:
首先栈的头文件是必须的(c++中):
#include<stack>
然后就是示例了:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<map>
#include<queue>
#include<stack> //栈的头文件
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define da 10000000
#define xiao -10000000
#define clean(a,b) memset(a,b,sizeof(a))
int main()
{
stack<int> s; //定义一个栈
s.push(1); //放入一个元素“1”;
printf("%d\n",s.top()); //输出栈顶元素
s.push(2); //再放入一个元素“2”;
printf("%d\n",s.top()); //输出栈顶元素
s.pop(); //取出站定的一个元素
printf("%d\n",s.top()); //输出栈顶元素
s.pop(); //再取出站定的一个元素
printf("%d\n",s.top()); //输出栈顶元素
}
他的运行结果如下:
这很明显就输出了三个数但我们有四个输出语句(printf),这是因为取出两个后栈的元素个数为零,于是运行错误了。。。。。。这个示例告诉我们栈为空时无法输出。。会错误;
好了,继续说题。。:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define da 100000
#define xiao -10000000
#define clean(a,b) memset(a,b,sizeof(a))
#define max 35000
int main()
{
double a,b;
char ch,jie,can;
while(scanf("%lf%c",&a,&can)) // 首先输入一个小数和一个字符,注意这里是字符,空格继续,\n结束
{
if(a==0&&can=='\n') //终止条件
break;
stack<double> suan; //建立一个栈;
suan.push(a);
while(scanf("%c %lf",&ch,&b)) //此处为输入一个进行一次运算
{
if(ch=='+') //符号为加
suan.push(b); //放入这个元素
else if(ch=='-') //放入这个元素的负数
suan.push(-b);
else if(ch=='*') //算数优先级的
{
double ji;
ji=suan.top()*b; //找到上一个元素
suan.pop(); //将他取出
suan.push(ji); //做乘法后再将结果放入栈
}
else
{
double shang; //除法与乘法类似
shang=suan.top()/b;
suan.pop();
suan.push(shang);
}
scanf("%c",&can); //判断是否输入结束
if(can=='\n')
break; //若输入结束则结束此次运算
}
double sum=0;
while(suan.size())
{
sum=sum+suan.top(); //把所有栈内的元素相加
suan.pop(); //加一个取出一个
}
printf("%0.2lf\n",sum); //最后输出取两位小数的结果
}
}
ok,栈的简单应用,还有其他应用,以后会补上(水平太菜。。。)