2016-01-22 117 views
5

我有一個字符表示運算符,共有四個運算符(+ - * /)。將char轉換爲算術運算符

我怎麼做的:

int Compute(char c, int a, int b) 
{ 
    if(c == '+') 
     return a+b; 
    else if(c == '-')  
     return a-b; 
    else if(c == '*') 
     return a*b; 
    else (c == '/') 
     return a/b; 
} 

有沒有更方便的方式來做到這一點?

+3

我認爲答案是否定的。 – Sahi

+3

「更方便」是什麼意思? –

+0

[有沒有一種方法可以將操作符轉換爲字符「+」爲算術的實際運算符?](http://stackoverflow.com/questions/19242330/is-there-a-way-i -can-convert-an-operator-as-a-char-into-the-actual-operator) – Henrik

回答

4

你可以使用switch語句:

int Compute(char c, int a, int b) 
{ 
    switch (c) { 
    case '+': return a+b; 
    case '-': return a-b; 
    case '*': return a*b; 
    case '/': return a/b; 
    default: throw std::runtime_error("No such operator"); 
    } 
} 
+0

您可以在除法 –

0

首先,語法

else (a == '/') 
    return a/b; 

是錯誤的,應該是

else if (a == '/') 
    return a/b; 

其次,你a參數只能取4個離散值,因此好的做法是使用一個枚舉,例如

enum Operation 
{ 
    kAddition, 
    kSubtraction, 
    kMultiplication, 
    kDivision 
}; 

int Compute(Operation a, int a, int b) 
{ 
    if (a == kAddition) 
     return a+b; 
    else if (a == kSubtraction)  
     return a-b; 
    else if (a == kMultiplication) 
     return a*b; 
    else if (a == kDivision) 
     return a/b; 
} 

其確保的Compute用戶將僅使用這四個值中的一個的操作(a)參數。

我可能沒有在我的例子中使用最佳實踐,所以我建議你閱讀this answer以獲得更多細節。

最後,你可以使代碼更簡潔使用switch語句:

enum Operation 
{ 
    kAddition, 
    kSubtraction, 
    kMultiplication, 
    kDivision 
}; 

int Compute(Operation a, int a, int b) 
{ 
    switch (a) 
    { 
     case kAddition: 
      return a+b; 
     case kSubtraction: 
      return a-b; 
     case kMultiplication: 
      return a*b; 
     case kDivision: 
      return a/b; 
    } 
} 
+0

是的,你說得對。但爲什麼其他(a =='/')是錯誤的? – Superxy

+0

@Superxy請參閱本教程以瞭解正確的語法。 http://www.cplusplus.com/doc/tutorial/control/ – Archimaredes

+0

我現在明白了,謝謝。 – Superxy

0
int ComputeByChar(char a, int c, int b) 
{ 
    switch(a) 
    { 
    case '+': return c+b; 
    case '-': return c-b; 
    case '/': return c/b; 
    case '*': return c*b; 
    default: cout<< "Invalid"; 
     break; 
    } 
    return 0; 
} 
+0

的情況下爲b!= 0添加檢查雖然這可以回答問題,但最好提供一些關於此代碼如何提供幫助的解釋。 – vard