#include <iostream>
#include <cstdio>
#include <string.h>
#include <ctype.h>
using namespace std;
double stDit[300];//数字栈
char stOp[300],str[300];//字符栈与字符串的栈
int top1,top2;
int Priority(char op)//先定义优先级的大小,方便下面进行比较
{
if (op=='#')
return 0;
if (op=='+' || op=='-')
return 1;
if (op=='*' || op=='/')
return 2;
else
return -1;
}
double Operate(double x,double y,char op)//计算
{
if (op=='+') return x+y;
if (op=='-') return x-y;
if (op=='*') return x*y;
if (op=='/') return x/y;
else return -1;
}
double Calc()
{
double x,y,tmp;
char op;
int i,n = strlen(str);
top1 = top2 = -1;
stOp[++top2] = '#';//栈头与栈尾都设为#
str[n++] = '#';
for(i=0; i < n; ++i)
{
if (str[i]==' ')
continue;
if (isdigit(str[i])) //是数字(自带函数,要记住)
{
//printf("i=%d\n",i);0
sscanf(str+i,"%lf",&tmp);//把数字读到变量tmp中, 再把tmp内容入栈; 最后把光标移到数这下一个字符。
//printf("str+i=%lf",str+i);0
// printf("1=%lf\n",str[i]);0
stDit[++top1] = tmp; //stack push
//printf("2=%lf\n",tmp);
while(isdigit(str[i+1])) //+1很重要
++i;
}
else //是操作符
{
while (Priority(stOp[top2]) >= Priority(str[i]))//如果操作栈顶的操作符优先级高,则作+-*/运算
{
if (str[i]=='#' && stOp[top2]=='#')
return stDit[top1];
y = stDit[top1--];
x = stDit[top1--];
op = stOp[top2--];
stDit[++top1] = Operate(x,y,op);
}
stOp[++top2] = str[i]; //如果新操作符优先级高,str[i]进栈
}
}
return stDit[top1];
}
int main()
{
int i;
while (gets(str) != NULL && strcmp(str,"0")!=0)//strcmp是比较函数,判定字符串是否都是0
{
printf("%.2lf\n",Calc());
}
return 0;
}
hdu1237计算器
最新推荐文章于 2022-09-26 23:14:02 发布