用栈实现简易计算器

近期学习的栈中就数计算器最难了!!!

后缀表达式的特点就是计算机运算非常方便,需要用到栈;计算机处理过程只需要顺序读入,如果遇到数字,则放入栈中,如果是运算符,则将两个栈中数字取出进行运算;
比如1+2的后缀表达式为12+;
而栈可以把一般的中缀表达式变成后缀表达式,并且计算后缀表达式得出结果,因此此应用在计算器中非常常用。
把中缀表达式转换成后缀表达式需要循几个规则:
(1)如果读入操作数,则直接放入输出字符串。
(2)如果读入一般运算符如+-*/,则放入堆栈,但是放入堆栈之前必须要检查栈顶,并确定栈顶运算符的优先级比放入的运算符的优先级低;如果放入的优先级较低,则需要将栈顶的运算符放入输出字符串。
(3)如果读入(,因为左括号优先级最高,因此放入栈中,但是注意,当左括号放入栈中后,则优先级最低。
(4)如果读入),则将栈中运算符取出放入输出字符串,直到取出(为止,注意:()不输出到输出字符串。
(5)顺序读完表达式,如果栈中还有操作符,则弹出,并放入输出字符串。
计算后缀表达式需要遵循以下几个规则:
(1)如果是操作数,则放入栈中。
(2)如果是操作符,则取出栈中两个操作数,进行运算后,将结果放入栈中。
(3)直到最后栈中只有一个元素,此元素就是计算结果。

#include<stdio.h>
#include<stdlib.h>

#define OK    100001
#define ERROR 100002
struct node
{
    int data;
    struct node *next;
};

typedef struct node Node;

struct stack
{
    Node *top;
    int count;
};

typedef struct stack Stack;


int InitStack(Stack *S)
{
    S->top = NULL;
    S->count = 0;

    return OK;
}


int EmptyStack(Stack *S)
{
    return (S->count == 0) ? OK : ERROR;
}


int Push(Stack *S, int e)
{
    Node *p = (Node *)malloc(sizeof(Node));
    if (NULL == p)
    {
        return ERROR;
    }
    p->data = e;
    p->next = S->top;
    S->top = p;
    S->count++;

    return OK;
}


int GetTop(Stack *S)
{
    if (NULL == S->top)
    {
        return ERROR;
    }

    return (S->top->data);
}


int Priority(char s)
{
    switch(s)
    {
        case '(':
            return 3;
        case '*':
        case '/':
            return 2;
        case '+':
        case '-':
            return 1;
        default :
            return 0;
    }
}


int Pop(Stack *S)
{
    int e;

    if (NULL == S->top)
    {
        return ERROR;
    }

    Node *p = S->top;
    e = p->data;
    S->top = p->next;
    free(p);
    S->count--;

    return e;
}
int main()
{
    char str[100] = {0};
    int i = 0, tmp = 0, j;
    Stack num, opt;

    if (InitStack(&num) != OK || InitStack(&opt) != OK)
    {
        printf("Init Failure!\n");
        exit(1);
    }

    printf("Please input operator :\n");
    scanf("%s",&str);

    while (str[i] != '\0' || EmptyStack(&opt) != OK)
    {
        if (str[i] >= '0' && str[i] <= '9')
        {
            tmp = tmp * 10 + str[i] - '0';
            i++;

            if (str[i] < '0' || str[i] >'9')
            {
                Push(&num, tmp);
                tmp = 0;
            }
        }

        else
        {
            if (EmptyStack(&opt) == OK || (GetTop(&opt) == '(' && str[i] != ')') || 
                Priority(str[i]) > Priority(GetTop(&opt)))
            {
                Push(&opt, str[i]);
                i++;
                continue;
            }

            if (GetTop(&opt) == '(' && str[i] == ')')
            {
                Pop(&opt);
                i++;
                continue;
            }

            if ((str[i] == '\0' && EmptyStack(&opt) != OK) || str[i] == ')' && GetTop(&opt) != '(' ||
                Priority(str[i]) <= Priority(GetTop(&opt)))
            {
                switch(Pop(&opt))
                {
                    case '+':
                        Push(&num, Pop(&num) + Pop(&num));
                        break;
                    case '-':
                        j = Pop(&num);
                        Push(&num, Pop(&num) - j);
                        break;
                    case '*':
                        Push(&num, Pop(&num) * Pop(&num));
                        break;
                    case '/':
                        j = Pop(&num);
                        Push(&num, Pop(&num) / j);
                        break;
                }

                continue;
            }
        }
    }

    printf("%d\n",Pop(&num));
    return 0;
}
  • 14
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是C++实现简易计算器的代码: ```c++ #include <iostream> #include <stack> #include <string> using namespace std; int main() { stack<int> numStack; // 存储数字的 stack<char> opStack; // 存储运算符的 string expression; // 表达式字符串 cin >> expression; int len = expression.length(); for (int i = 0; i < len; i++) { char ch = expression[i]; if (ch >= '0' && ch <= '9') { // 如果是数字,入数字 numStack.push(ch - '0'); } else { // 如果是运算符 if (opStack.empty() || ch == '(') { // 如果运算符为空或者当前运算符是左括号,直接入 opStack.push(ch); } else if (ch == ')') { // 如果当前运算符是右括号,弹出运算符中的元素直到遇到左括号 while (opStack.top() != '(') { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } opStack.pop(); // 弹出左括号 } else { // 如果当前运算符是加减乘除 while (!opStack.empty() && opStack.top() != '(' && ((ch == '*' || ch == '/') || (opStack.top() == '+' || opStack.top() == '-'))) { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } opStack.push(ch); } } } while (!opStack.empty()) { // 处理剩余的运算符 int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } cout << numStack.top() << endl; // 输出最终结果 return 0; } ``` 这个程序可以处理包含加减乘除和括号的表达式,但是没有考虑负数的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生卍流年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值