四则运算计算机C++项目练习

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include "mystack.h"
#include "myqueue.h"

#define DEBUG               0
#define MAX_LENGTH_TXT      500

typedef enum {
    ERR_NONE = 0,
    ERR_IO,
    ERR_STACK,
    ERR_QUEUE
} errNum;

typedef struct {
    errNum error;
    int line;
} myError;

int getExpr(char expr[]);
myError processQueue(char expr[], int len_txt);
double calcQueue();
char* zeroRid(double num);

int main() {
    char expr[MAX_LENGTH_TXT];
    int len_txt = 0;
    myError err;
    double res;

    while (1) {
        stackClean();
        queueClean();
        printf("please input a expression (Supported operators '+ - * / ( )' and Bracket nesting) or 'q' to exit\n> ");
        len_txt = getExpr(expr);                // 获取输入
        if (len_txt == -1) {
            break;
        } else if (len_txt == 0) {
            continue;
        }
#if (DEBUG == 1)
        printf("> %s | Length: %d\n", expr, len_txt);
#endif
        err = processQueue(expr, len_txt);      // 处理表达式
        if (err.error == ERR_IO) {
            printf("[ERROR_IO]: (Line: %d)Please check the input carefully and try again later\n", err.line);
            continue;
        } else if (err.error == ERR_QUEUE) {
            printf("[ERROR_QUEUE]: (Line: %d)Queue full, input too long please try again\n", err.line);
            continue;
        } else if (err.error == ERR_STACK) {
            printf("[ERROR_STACK]: (Line: %d)Stack full, input too long please try again\n", err.line);
            continue;
        }
#if (DEBUG == 1)
        printf("> ");
        queuePrint();
#endif
        res = calcQueue();                      // 计算结果
        printf("= %s\n", zeroRid(res));
    }

    return 0;
}

/* 获取运算符优先级 */
uint8_t priority(char symbol) {
    switch (symbol) {
        case '+':
        case '-': return 1;
        case '*':
        case '/': return 2;
        case '(': return 3;
    }
    return 0;
}

/* 从标准输入中读入一行表达式 
 * 返回读入的字符串长度
 * -1 表示输入为退出标记或栈满退出
 */
int getExpr(char expr[]) {
    char ch;
    int len_txt = 0;
    while (1) {
        ch = getchar();
        if (ch == 'q') {  // 输入q, 直接退出
            len_txt = -1;
            break;
        }
        if ((ch >= '0' && ch <= '9') || ch == '.' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')') {
            /* 输入过滤 */
            expr[len_txt++] = ch;
            if (len_txt >= MAX_LENGTH_TXT) {
                len_txt = -1;  
                break;  // 输入溢出
            }
        } else if (ch == '\n') {
            expr[len_txt] = '\0';
            break;
        }
    }
    return len_txt;
}

/* 处理中序表达式,以逆波兰形式存入队列
 * 没有错误,返回0
 */
myError processQueue(char expr[], i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值