1/18巧妙利用栈实现计算器

在这里中缀表达式转后缀表达式我主要采用了两个数组和一个栈实现,这个栈首先是来保存运算符,通过数组和栈配合实现后缀表达式,然后为了得到结果,使用了strtok()函数,这个函数用来字符串分割,最终可以得到结果。

详细代码如下:

cal.h

#define _CRT_SECURE_NO_WARNINGS 1


#ifndef __CAL_H__

#define __CAL_H__

//利用顺序栈实现计算器

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

#define MAXSIZE 50


typedef int SElemType;

//定义一个顺序存储栈
typedef struct
{
    SElemType data[MAXSIZE];
    int top;
}SqStack;


int To_PostFix(char *infix, char *postfix);

int  Calculator(char *postfix, int *result);



#endif // !__CAL_H__

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

cal.c

#define _CRT_SECURE_NO_WARNINGS 1

#include"cal.h"



/*******************栈的基本操作********************************/
int init_stack(SqStack *s)
{
    s->top = -1;
    return 1;
}

int clear_stack(SqStack *s)
{
    s->top = -1;
    return 1;
}

int stack_empty(SqStack s)
{
    if (s.top == -1)
        return 1;
    else
        return 0;
}

int stack_length(SqStack *s)
{
    return s->top + 1;
}

int push(SqStack *s, SElemType e)
{
    if (s->top == MAXSIZE - 1)
        return 0;
    s->top++;
    s->data[s->top] = e;
    return 1;
}

int pop(SqStack *s, SElemType *e)
{
    if (s->top == -1)
        return 0;
    *e = s->data[s->top];
    s->top--;
    return 1;
}

/*******************中序表达式转换为后续表达式********************************/
int To_PostFix(char *infix, char *postfix)
{
    SqStack s;
    int e = 0;
    int i = 0, j = 0;
    int flag = 0;

    if (init_stack(&s) != 1)   //判断栈是否为空,
        return 0;

    while (infix[i] != '\0')   //说明栈中有元素。
    {

        while (infix[i] >= '0' && infix[i] <= '9')    //如果是数字则输出
        {
            if (flag) //考虑负数的情况
            {
                flag = 0;
                postfix[j++] = '-';
            }
            postfix[j++] = infix[i];//让存放后缀表达式的数组存放字符
            i++;
            if (infix[i]<'0' || infix[i]>'9') //判断是否为操作符,如果是,让后缀表达式中存放一个' '
                postfix[j++] = ' ';
        }
        if (infix[i] == ')' )       //如果是关于括号的符号,则进行栈操作
        {
            pop(&s, &e);
            while (e != '(' )
            {
                postfix[j++] = e;
                postfix[j++] = ' ';
                pop(&s, &e);
            }
        }
        else if (infix[i] == '+' || infix[i] == '-') //对于同运算级的+和-操作
        {
            if (infix[i] == '-' && (i == 0 || (i != 0 && (infix[i - 1]<'0' || infix[i - 1]>'9'))))  //当'-'号处于第一位,或前面是符号时,为负号标志
                flag = 1;
            else if (stack_empty(s))
                push(&s, infix[i]);
            else
            {
                do
                {
                    pop(&s, &e);
                    if (e == '(' )
                        push(&s, e);
                    else
                    {
                        postfix[j++] = e;
                        postfix[j++] = ' ';
                    }
                } while (!stack_empty(s) && e != '(' );
                push(&s, infix[i]);
            }
        }
        else if (infix[i] == '*' || infix[i] == '/' || infix[i] == '(' )//对于乘除以及括号的开始进行压栈
            push(&s, infix[i]);
        else if (infix[i] == '\0')
            break;
        else
            return 0;
        i++;
    }

    while (!stack_empty(s))
    {
        pop(&s, &e);
        postfix[j++] = e;
        postfix[j++] = ' ';
    }

    clear_stack(&s);
    return 1;
}

/*******************根据后续表达式计算结果********************************/
int  Calculator(char *postfix, int *result)
{
    SqStack s;
    char *op; //存放后缀表达式中的每个因数或运算符  
    char *buf = postfix; //声明bufhe saveptr两个变量,是strtok_r函数的需要。  
    char *saveptr = NULL;
    int d, e, f;

    if (init_stack(&s) != 1)
        return 0;

    while ((op = strtok(buf, " ")) != NULL)//利用字符串分割函数
    {
        buf = NULL;                     //把指针置空
        switch (op[0])
        {
        case '+':
            pop(&s, &d);
            pop(&s, &e);
            f = d + e;
            push(&s, f);
            break;
        case '-':
            if (op[1] >= '0' && op[1] <= '9')    //是负号而不是减号
            {
                d = atoi(op);
                push(&s, d);
                break;
            }
            pop(&s, &d);
            pop(&s, &e);
            f = e - d;
            push(&s, f);
            break;
        case '*':
            pop(&s, &d);
            pop(&s, &e);
            f = e*d;
            push(&s, f);
            break;
        case '/':
            pop(&s, &d);
            pop(&s, &e);
            f = e / d;
            push(&s, f);
            break;
        default:                //考虑数字的情况,进行atoi函数进行转化
            d = atoi(op);
            push(&s, d);        //进行压栈
            break;
        }
    }
    pop(&s, result);
    clear_stack(&s);
    return 0;
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186

test.c

#define _CRT_SECURE_NO_WARNINGS 1

#include"cal.h"


void Test()
{

    char infix[MAXSIZE] = { 0 };
    char postfix[MAXSIZE] = { 0 };
    int result = 0;
    printf("请输入一个中缀表达式:\n");
    scanf("%s", infix);
    fflush(stdin);
    To_PostFix(infix, postfix);
    printf("转换得到的后缀表达式是:\n");
    printf("%s\n", postfix);
    Calculator(postfix, &result);
    printf("最后得到的结果:\n");
    printf("%d\n", result);


}

int main()
{
    Test();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来解答你的问题。 下面是一个基于的C语言计算器法运算实现的示例代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct stack { int top; // 顶指针 int data[MAX_SIZE]; // 的数组 } Stack; // 初始化 void init(Stack *s) { s->top = -1; } // 判断是否为空 int is_empty(Stack *s) { return s->top == -1; } // 判断是否已满 int is_full(Stack *s) { return s->top == MAX_SIZE - 1; } // 入 void push(Stack *s, int element) { if (is_full(s)) { printf("Stack is full.\n"); exit(1); } s->data[++s->top] = element; } // 出 int pop(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } return s->data[s->top--]; } // 获取顶元素 int get_top(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } return s->data[s->top]; } // 计算器法运算 int calculator(char *str) { Stack s; init(&s); int i = 0; while (str[i] != '\0') { if (str[i] >= '0' && str[i] <= '9') { // 如果是数字字符,则将其转换为数字压入中 int num = str[i] - '0'; while (str[i + 1] >= '0' && str[i + 1] <= '9') { num = num * 10 + str[i + 1] - '0'; i++; } push(&s, num); } else if (str[i] == '+') { // 如果是号,则将顶的两个元素弹出相后再将结果压入中 int num1 = pop(&s); int num2 = pop(&s); push(&s, num1 + num2); } i++; } return get_top(&s); } int main() { char str[100]; printf("Please input the expression: "); scanf("%s", str); int result = calculator(str); printf("Result: %d\n", result); return 0; } ``` 以上就是一个基于的C语言计算器法运算实现的示例代码,希望能帮助到你。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值