解析简单的算术表达式(不含括号),如: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;
}