恐怕您必须像这样处理 switch 或语句中的每个运算符:
switch(operator){
case '+': // Note that this works only for scalar values not string
result = number1+number2;
// ...
}
头韵你可以像这样准备操作员回调列表:
typedef int (*operator_callback) (int operand1, int operand2);
typedef struct {
char name;
operator_callback callback;
} operator_definition;
int operator_add(int x, int y) {return x+y;}
int operator_minus(int x, int y) {return x-y;}
// And prepare list of those
operator_definition[] = {
{'+', operator_add},
{'-', operator_minus},
{NULL, NULL}
};
// Function for fetching correct operator callback
operator_callback get_operator_callback(char op)
{
int i;
for( i = 0; operator_definition[i].name != NULL; ++i){
if( operator_definition[i].name == op){
return operator_definition[i].callback;
}
}
return NULL;
}
// And in main function
operator_callback clbk = get_operator_callback(operator);
if( !clbk){
printf( "Unknown operator %c\n", operator);
return -1;
}
result = clbk(number1, number2);