恐怕你必须处理的开关或语句中的每个运营商这样的:
switch(operator){
case '+': // Note that this works only for scalar values not string
result = number1+number2;
// ...
}
Alliteratively你可以准备这样的操作回调列表:
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);
好多了:-) – Mat 2013-04-21 13:06:44