關於計算器的題目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;
}