关于计算器的题目http://ac.jobdu.com/problem.php?pid=1019,该题要编写的计算器比一般的计算器简单,因为不含括号,运算优先级就两种,先算乘除法就好,这是受到了fripSide同学的启发,不需要算术符号栈,只需要数字栈,遇加减号就将下一个数字入栈(遇减号将数字反号入栈),遇乘除号,就将栈顶的数字取出运算后再入栈。当处理完整个计算式时,将栈中的所有数取出相加,既得结果。代码如下
#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;
stack <double> num;
int main()
{
double a;
char b;
while (scanf("%lf",&a)!=EOF&&a!=0)
{
while (!num.empty()) num.pop();
num.push(a);
while (scanf("%c", &b)!=EOF)
{
while (b==' ') b=getchar();
if (b=='\n') break;
scanf("%lf",&a);
if (b=='+') num.push(a);
if (b=='-') num.push(-a);
if (b=='*')
{
double temp1=a*num.top();
num.pop();
num.push(temp1);
}
if (b=='/')
{
double temp2=num.top()/a;
num.pop();
num.push(temp2);
}
}
double ans=0;
while (!num.empty())
{
ans+=num.top();
num.pop();
}
printf("%.2lf\n",ans);
}
return 0;
}