C语言,基于递归下降的计算器程序。缺点,不支持小括号。

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

char *p, *src;
void error(const char *s){
    printf("%s\n", src);
    char fmt[80];
    sprintf(fmt, "%%%lds\n", p - src);
    printf(fmt, "^");

    printf("错误:%s\n", s);
    exit(EXIT_FAILURE);
}

int c;
float val;

float num(){
    while (isspace(c = *p)){
        p++;
    }
    bool sign = false;
    if (c == '+'){
        c = *++p;
    }else if (c == '-'){
        sign = true;
        c = *++p;
    }
    while (isspace(c = *p)){
        p++;
    }
    if (isdigit(*p) == 0){
        error("缺少数字");
    }

    int x = 0;
    float xx = 0;
    bool bxx = 0;
    int n=0;
    while (isdigit(c = *p) || c == '.'){
        if (c == '.'){
            bxx = 1;
            p++;
            continue;
        }
        if (!bxx)
            x = x * 10 + (c - '0');
        else{
            xx +=((c - '0') /pow(10,++n));
        }
        p++;
    }
    while (isspace(c = *p)){
        p++;
    }
    float val = (float)x +xx;
    return sign ? -val : val;
}
float m(){
    float mx = num();
    while (c == '*' || c == '/'){
        ++p;
        if (c == '*'){
            mx *= num();
        }else{
            mx /= num();
        }
    }
    return mx;
}
void parse(){
    if (c == '+'){
        c = *++p;
        val += m();
    }else if (c == '-'){
        c = *++p;
        val -= m();
    }else{
        error("缺少运算符");
    }
}

float calc(){
    p = src;
    c = *p;
    val = 0;
    if (c){
        val = m();
        while(c) parse();
    }
    return val;
}

/*
1 + 2 * 3
42 *3.14159
1+2*3/4-5
1/2/3/4/5
*/
int main(){
    src = p = (char *)malloc(1024);
    while (fgets(src, 1024, stdin)){
        char *ptr = strchr(src, 10);
        if (ptr)*ptr = 0;
        printf("=%f\n", calc());
    }
    free(src);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值