栈实现简单的计算器

这篇博客介绍了如何使用栈来实现一个简单的计算器,通过建立两个栈分别存放运算符和操作数,根据运算符的优先级进行计算,处理括号等复杂情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上个星期的作业,现在才改好。。。。。

基本思路:

当我们从键盘上输入一串字符,比如1+(2+3),建立两个栈,一个存放运算符的栈toperator,一个存放操作数number,依次遍历。

遇到操作数就依次存放到操作栈里;

遇到运算符时,优先级高的就直接压进运算符栈里,优先级低的就依次弹出操作栈中的两个值与运算符进行计算,然后把计算的值再次压进操作数栈里。其中有括号的情况,左括号的直接压进,当右括号遇到左括号的时候就直接弹出左括号。


程序:

类模块:

#ifndef _STACK_H_
#define _STACK_H_

#include<iostream>

using namespace std;

template<typename T>
class Stack
{
public:
   Stack(int maxSIZE);
   ~Stack();
   void Push(const T& n);
   void Pop();
   T& getTop() const;
   bool Empty() const;
private:
    T *s_;
    int top_;
    int maxSIZE_;
};

template <typename T>
Stack<T>::Stack(int maxSIZE):maxSIZE_(maxSIZE),top_(-1)
{
    s_ = new T[maxSIZE];
}

template<typename T>
Stack<T>::~Stack()
{
    delete []s_;
}

template<typename T>
void Stack<T>::Push(const T& n)
{
    if(top_ == maxSIZE_-1)
    {
        throw(1);
    }
    top_++;
    s_[top_] = n;
}

template<typename T>
void Stack<T>::Pop()
{
    if(Empty() == true)
    {
        throw(1);
    }
    top_--;
}

template<typename T>
T& Stack<T>::getTop() const
{
    if(Empty() == true)
    {
        throw(1);
    }
    return s_[top_];
}

template<typename T>
bool Stack<T>::Empty()const
{
    return top_+1 == 0;
}

#endif


#include<iostream>
#include"stack.h"
#include<cstdlib>
#include<cstring>

using namespace std;

Stack<int> number(100);
Stack<char> toperator(100);

int calsum(int a,int b,char ope)//计算过程
{
    if(ope == '*')
    {
        b = b*a;
    }

    if(ope == '/')
    {
        b = b/a;
    }
    
    if(ope == '+')
    {
        b = b+a;
    } 

    if(ope == '-')
    { 
        b = b-a;
    }
    
    return b;
}

int priority(char ch)//优先级
{    

    if(ch == '(' || ch == ')')
    {
        return -1;
    }
    if(ch == '+' || ch == '-')
    {
        return 0;
    }
    if(ch == '*' || ch == '/')
    {
        return 1;
    }
}

int is_number(char ch)//判断是数字还是运算符
{
    if(ch >= '0' && ch <= '9')
    {
        return 1;
    }
    return 0;
}
int calculate(char* buffer)
{
    int i = 0;
    int a;
    int b;
    int sum;

    while(buffer[i] != '\0')
    {

        if((is_number(buffer[i])) == 1)//是字符数字
	{
	    int num = buffer[i] - '0';//将字符转换为数字
	    number.Push(num);//将操作数压栈
	}
	if((is_number(buffer[i])) == 0)//是运算符
	{
	    if((toperator.Empty()) == 1)
	    {
	        toperator.Push(buffer[i]);//首次压栈
	    }
	    else//不是第一次压栈
	    {    
	        if((priority(buffer[i]))>(priority(toperator.getTop())) || buffer[i] == '(')//优先级高的入栈
	        {
	            toperator.Push(buffer[i]);
	        }
	        else
	        {
		    a = number.getTop();
		    number.Pop();

		    b = number.getTop();
	            number.Pop();
                        
	            b = calsum(a,b,toperator.getTop()); 
			
                    number.Push(b);
                    toperator.Pop();

		    if(toperator.getTop() == '(' && buffer[i] == ')')
		    {
		        toperator.Pop();//当两个括号相遇的时候,删除左括号
		    }
                 }
	      }
	}
	i++;//往后依次遍历
    }
    while(toperator.Empty() != true)//遍历结束,但是栈中还有数
    {
        a = number.getTop();
        number.Pop();

        b = number.getTop();
        number.Pop();
                   
        b = calsum(a,b,toperator.getTop());      

        number.Push(b);
        toperator.Pop();
    }
    return b;
}

int main()
{
    char buffer[100];
    
    int sum;
    
    cout<<"please input a string:\n"<<endl;
    cin>>buffer;
    try
    {
        sum = calculate(buffer);
    
        printf("the sum is %d\n",sum);   
    }

    catch(int a)
    {
        cout<<"number failed"<<__LINE__<<endl;
    }
    catch(char ch)
    {
        cout<<"operator failed"<<__LINE__<<endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值