假设我想从用户那里接收两个数学运算(例如 + - %
)并相应地计算数字。还假设我可以使用 one if/else
语句来确定优先级(并且所有操作都有不同的优先级)。
我心中有几个实现想法,并且希望获得关于哪种编码被认为是“更好”的反馈(更清晰、更高效等)。
我可以做这样的事情:
if (firstOperator >= secondOperator){ switch (firstOperator){ case '+': switch (secondOperator) // insert all 6 possible cases case '-': switch (secondOperator) // insert all 5 possible cases ... ... } else{ // same idea as above }
或者我可以通过为
firstOperation
的每个选项创建一个switch
来简单地硬编码所有选项,并嵌套第二个switch
> 在所有可能的第二次操作
的每种情况
中。
两种做法不同,我还有一两个。我本以为第一个更“正确”和优雅,但它实际上比“暴力”全力以赴的第二个选项产生更多的代码行。
我很想听到有关此类编码的任何意见。
注意:我只讨论非常基本的 C 编程(即不使用堆栈等其他数据结构。只有基本的 if/else
、开关
、循环
等
最佳答案
这是我的做法,但这取决于你的第一个和第二个操作是否独立处理(我认为如果你正在做的是一个表达式求值器,这应该是可能的)。在我的示例中,我假设有一个队列保存按解析顺序解析的参数。
if (firstOperator >= secondOperator) {
handle(firstOperator);
handle(secondOperator);
} else {
// Assuming something like 1 + 2 * 3, with 1 2 3 in the queue:
//
// tmp = dequeueArg() makes the queue: 2 3
// handle('*') makes the queue: 6
// pushFront(tmp) makes the queue: 1 6
// handle('+') makes the queue: 7
//
int tmp = dequeueArg();
handle(secondOperator);
pushFront(tmp);
handle(firstOperator);
}
void handle(Op operator)
{
int x = dequeueArg();
int y = dequeueArg();
switch (operator) {
case '+': pushFront(x+y); break;
case '-': pushFront(x-y); break;
case '*': pushFront(x*y); break;
case '/': pushFront(x/y); break; // Maybe check for 0
case '%': pushFront(x%y); break; // Maybe check for 0
case '&': pushFront(x&y); break;
etc...
}
}
我在这里写的内容可能无法作为具有优先级的通用中缀解析器。它更多地是如何不使用 O(N^2) 嵌套 case 语句的示例。
关于c - 处理作为输入接收的数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917843/