![](/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.