简单,好用,安全 #include <cstdio> #include <exception> #include <cctype> using namespace std; char data[128]; int i; double expr(); void match( int key ) { if( data[i] != key ) throw exception("输入错误"); ++i; } double factor() { if( data[i] == '(' ) { match('('); double mid = expr(); match(')'); return mid; } else { if( !isdigit( data[i] )) match('/0'); int result = 0 ; for( ; isdigit(data[i]) ; ++i ) result = result * 10 + data[i] - '0'; return result; } } double term() { double cur = factor(); while( true ) { if( data[i] == '*' ) { match('*'); cur = cur * factor(); } else if( data[i] == '/' ) { match('/'); cur = cur / factor(); } else return cur; } } double expr() { double cur = term(); while( true ) { if( data[i] == '+' ) { match('+'); cur = cur + term(); } else if( data[i] == '-' ) { match('-'); cur = cur + term(); } else return cur ; } } int main() { try { scanf("%s",data); i = 0; double cur = expr(); match('/0'); printf("结果 %lf/n",cur ); } catch( exception & e ) { printf("%s/n",e.what()); } return 0; }