解析简单的算术表达式(第1版)

解析简单的算术表达式(不含括号),如:2*12/3+3*9/1-3=

这一版本目前尚未添加对特殊情况的处理,如分母为0的情形、表达式中含有非法字符的情形等。


#include <stdio.h>

// 解析只含乘除法的算术表达式
//
int parse_expr( char * p, char * q )
{
    int a = 0, b = 0;
    char op;

    while( *p >= '0' && *p <= '9' ) {
        a = a * 10 + ( *p++ - '0' );
    }

    while( p <= q ) {
        if( *p == '*' || *p == '/' ) {
            op = *p++;
        }
        else if( *p == '+' || *p == '-' ) {
            break;
        }

        b = 0;
        while( *p >= '0' && *p <= '9' ) {
            b = b * 10 + ( *p++ - '0' );
        }
        if( op == '*' ) a *= b;
        else if( op == '/' ) a /= b;
    }
    return a;
}

int main()
{
    char expr[100] = { '\0' };
    char *p = NULL, *q = NULL;
    char op;
    int a, b, c;
 
    gets( expr );
    
    q = p = expr;
    while( *q != '\0' && *q != '+' && *q != '-' ) {
        ++q;
    }
    a = parse_expr( p, q - 1 );    
    p = q + 1;
    while( 1 ) {
        op = *q++;
        while( *q != '+' && *q != '-' && *q != '=' ) {
            ++q;
        }
        b = parse_expr( p, q - 1 );
        p = q + 1;
        if( op == '+' ) a += b;
        else a -= b;
        if( *q == '=' ) break;
    }
    printf( "%d\n", a );
    system( "pause" );
    return 0;
}

int parse_number( char * p, char * q )
{
    int n = 0;
    while( p <= q ) {
        n = n * 10 + ( *p++ - '0' );
    }
    return n;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值