![](/img/trans.png)
[英]C Console Program using User Input ('+' / '-') for Mathematical operations not functioning
[英]Working with mathematical operations received as input
假设我想从用户那里接收两个数学运算(例如+ - %
)并据此计算数字。 我们也可以使用一个 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
来简单地对所有选项进行硬编码,并在每种cases
为所有可能的secondOperation
嵌套第二个switch
。
两种方法不同,我还有一种或两种。 我以为第一个选项更“正确”且美观,但实际上比“蛮力”第二个选项所产生的代码行更多。
我很想听听有关这种编码的任何输入。
注意:我在说的只是非常基本的C编程(即,不使用栈等其他数据结构。仅是基本的if/else
, switch
, loops
等)。
这是我的操作方式,但这取决于您要独立处理的第一个和第二个操作(如果您正在做的是表达式求值器,我认为这应该是可能的)。 在我的示例中,我假设有一个队列,其中包含按解析顺序解析的参数。
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...
}
}
我在这里写的内容可能无法作为具有优先级的常规infix解析器使用。 它是如何不使用O(N ^ 2)嵌套case语句的一个示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.