简单计算器(浙江大学)

本文介绍了一个使用C++编写的程序,它通过栈来解析和计算带有运算符的算术表达式,包括加减乘除操作。程序逐个处理输入的字符,根据运算符优先级决定何时执行计算。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<vector>
#include<cstdio>
#include<queue>
#include<stack>
#include<cctype> //有isdigit函数,用来判断是否是十进制数

using namespace std;

int Priority(char c)        //优先级
{
    if(c=='#')
        return 0;
    else if(c=='$')
        return 1;
    else if(c=='+'||c=='-')
        return 2;
    else
        return 3;
}

double GetNumber(string str,int& index)   //接着获得下一个数字
{
    double number=0;
    while(isdigit(str[index]))
    {
        number=number*10+str[index]-'0';//比如114,按照1,1,4的顺序扫描,然后计算出来该数字
        index++;
    }
    return number;
}

double Calculate(double x,double y,char op)
{
    double result=0;
    if(op=='+')
        result=x+y;
    else if(op=='-')
        result=x-y;
    else if(op=='*')
        result=x*y;
    else if(op=='/')
        result=x/y;
    return result;
}
int main(){
    string str;
    while(cin>>str)
    {
        if(str=="0")
            break;
        int index=0;         //字符串下标
        stack<char> oper;   //运算符栈
        stack<double> data; //运算数栈
        str+='$';            //字符串尾部添加$
        oper.push('#');      //运算符栈底添加#
        while(index<str.size())
        {
            if(str[index]==' '){
                index++;
            }
            else if(isdigit(str[index])){
                data.push(GetNumber(str,index));
            }else{
                if(Priority(oper.top())<Priority(str[index])){    //比较优先级,栈顶的优先级更低,把新的运算符压入栈中,继续扫描下一个字符
                    oper.push(str[index]);
                    index++;
                }else{                                       //弹出栈顶的两个数进行计算
                    double y=data.top();
                    data.pop();
                    double x=data.top();
                    data.pop();
                    data.push(Calculate(x,y,oper.top()));
                    oper.pop();
                }
            }
        }
        printf("%.2f",data.top());
    }
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值