hdu1237计算器


#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值