栈实现计算器

        前段时间利用栈写了一个实现了计算器功能的程序。觉得有意思的,因此今天在这了和大家分享一番。

        首先,要写出计算器,你要按照以下几点去写,才能保证运算的优先级不发生错误。

  1. 自左向右扫描表达式,凡是遇到操作数一律进操作数栈。
  2. 当遇到运算符时,如果他的优先级比运算符栈栈顶元素的优先级高就栈。反之,取出栈顶运算符和操作数栈顶的两个连续操作数运算,并将结果存入操作数栈,然后继续比较该运算符与栈顶的运算符的优先级。
  3. 左括号一律进运算符栈,右括号一律不进运算符栈,取出栈顶运算符和操作数栈顶的两个连续操作数运算,并将结果存入操作数栈,直到取出左括号为止。

        希望大家可以自己独立完成。因为这个是有难度的,可以写在自己以后简历上。

附上我写的程序,可供大家参考。

/*****************************************************
File name:calculator
Author:谢艺化    Version:1.0    Date: 2016-6-12
Description:可以作为简单的计算器,实现加,减,乘,除,以及带括号的运草
Calls : 1.insert_operand ()     输入数据
        2.insert_oper()         输入操作符
        3.compare()             比较操作符优先级
        4.deal_date()           进行数据处理
*****************************************************/

#include <stdio.h>                          /*包含头文件*/
#define MAX_SIZE 1024                       /*数组长度*/

int insert_operand(int *operand , int * top_num ,int num)           /*数据压入数据栈*/
{
    (*top_num) ++;
    operand[*top_num] = num;                    /*保存数据*/
    
    return 0;                           /*正常退出*/
}

int insert_oper (char * oper , int *top_oper , char ch)             /*操作符压入符号栈*/
{
    (*top_oper)++;
    oper[*top_oper] = ch;                       /*保存操作符*/

    return 0;                           /*正常退出*/
}

int compare(char *oper , int *top_oper , char ch)                   /*比较操作服优先级*/
{   
   
    if((oper[*top_oper] == '-' || oper[*top_oper] == '+')           /*判断当前优先级是否比栈顶操作符优先级高*/
            && (ch == '*' || ch == '/'))
    {
        return 0;                      /*操作符压入栈*/ 
    }

    else if(*top_oper == -1 || ch == '(' 
            || (oper[*top_oper] == '(' && ch != ')'))       /*判断操作符栈是否为空;栈顶操作                                                               符是否为'('*/
    {
        return 0;                       /*操作符压入栈*/
    }

    else if (oper[*top_oper] =='(' && ch == ')' )       /*判断括号内的表达式是否计算完毕*/
    {
        (*top_oper)--;
        return 1;                       /*对()进行处理*/
    }

    else
    {
        return -1;                                          /*进行操作符的运算*/
    }

}

int deal_date(int *operand ,char *oper ,int *top_num, int *top_oper)    /*进行数据运算*/
{
    int num_1 = operand[*top_num];              /*取出数据栈中两个数据*/
    int num_2 = operand[*top_num - 1];

    int value = 0;

    if(oper[*top_oper] == '+')                  /*加法操作*/
    {
        value = num_1 + num_2;
    }

    else if(oper[*top_oper] == '-')             /*减法操作*/
    {
        value = num_2 - num_1;
    }

    else if(oper[*top_oper] == '*')             /*乘法操作*/
    {
        value = num_2 * num_1;
    }

    else if(oper[*top_oper] == '/')             /*除法操作*/
    {
        value = num_2 / num_1;
    }

    (*top_num) --;                              /*将数据栈顶下移一位*/
    operand[*top_num] = value;                  /*将得到的值压入数据栈*/
    (*top_oper) --;                             /*将操作符栈顶下移一位*/


}

int main()
{
    int operand[MAX_SIZE] = {0};                /*数据栈,初始化*/
    int  top_num = -1;

    char oper[MAX_SIZE] = {0};                  /*操作符栈,初始化*/
    int top_oper = -1;

    char *str = (char *) malloc (sizeof(char) * 100);               /*获取表达式(不带=)*/
    scanf("%s",str);

    char* temp;
    char dest[MAX_SIZE];
    int num = 0;

    int i = 0;
    while(*str != '\0')
    {
        temp = dest;

        while(*str >= '0' && *str <= '9')           /*判断是否是数据*/
        {
            *temp = *str;
            str ++;
            temp ++;                
        }                               /*遇到符号退出*/

        if(*str != '(' && *(temp - 1) != '\0')      /*判断符号是否为'('*/
        {
            *temp = '\0';

            num = atoi(dest);               /*将字符串转为数字*/
            insert_operand(operand, &top_num,num);      /*将数据压入数据栈*/
        }

         while(1)
         {
             i = compare(oper,&top_oper,*str);      /*判断操作符优先级*/

            if(i == 0)
            {
                insert_oper(oper,&top_oper,*str);   /*压入操作符*/
                break;
            }

            else if(i == 1)                         /*判断括号内的表达式是否结束*/
            {
                str++;
            }

            else if(i == -1)                        /*进行数据处理*/
            {
                deal_date(operand,oper,&top_num,&top_oper);
            }

         }

        str ++;                 /*指向表达式下一个字符*/
    }

    printf("num = %d\n",operand[0]);        /*输出结果*/

    return 0;                       /*正常退出*/
}

如果有不足的地方,欢迎大家留言,帮助我改进。

若我的内容对您有所帮助,还请关注我的公众号。不定期分享干活,剖析案例,也可以一起讨论分享。

我的宗旨:

踩完您工作中的所有坑并分享给您,让你的工作无bug,人生尽是坦途

=====================================================================
更新于2023.11.16,感谢未来的自己,送来满意的答卷

【献给过去的自己】栈实现计算器(C语言)-CSDN博客

  • 9
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
以下是用实现计算器的 C 语言代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct { int top; double data[MAX_SIZE]; } Stack; void init(Stack *s) { s->top = -1; } int isEmpty(Stack *s) { return s->top == -1; } int isFull(Stack *s) { return s->top == MAX_SIZE - 1; } int push(Stack *s, double x) { if (isFull(s)) { return 0; } s->top++; s->data[s->top] = x; return 1; } int pop(Stack *s, double *x) { if (isEmpty(s)) { return 0; } *x = s->data[s->top]; s->top--; return 1; } int peek(Stack *s, double *x) { if (isEmpty(s)) { return 0; } *x = s->data[s->top]; return 1; } int calculate(double a, double b, char op, double *result) { switch (op) { case '+': *result = a + b; break; case '-': *result = a - b; break; case '*': *result = a * b; break; case '/': if (b == 0) { return 0; } *result = a / b; break; default: return 0; } return 1; } int main() { Stack s; init(&s); char c; double x, a, b, result; while (scanf("%c", &c) != EOF) { if (c >= '0' && c <= '9') { ungetc(c, stdin); scanf("%lf", &x); push(&s, x); } else if (c == '+' || c == '-' || c == '*' || c == '/') { if (pop(&s, &b) && pop(&s, &a)) { if (calculate(a, b, c, &result)) { push(&s, result); } else { printf("Invalid expression\n"); return 1; } } else { printf("Invalid expression\n"); return 1; } } else if (c == '\n') { if (peek(&s, &result) && isEmpty(&s)) { printf("%.2f\n", result); } else { printf("Invalid expression\n"); return 1; } init(&s); } } return 0; } ``` 该程序通过读入一个字符,如果是数字,则将其转换为浮点数并压入中;如果是运算符,则从中弹出两个数进行相应的运算,并将结果压入中;如果是换行符,则输出顶元素(即最终结果),并清空。在计算过程中,如果空或顶元素不够两个,则输出错误信息并退出程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

谢艺华

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

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

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

打赏作者

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

抵扣说明:

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

余额充值