2014-10-26 67 views
-5

如何使用數字參數創建操作方法(int op),以便通過操作(1)或操作(3)調用其他方法?我想我需要創建一個開關,但我不知道如何。C++中的調用方法

int subtraction(int n1, int n2) { //e.g. of simple method 
    return n1 - n2; 
} 

int multiplication (int n1, int n2){ 
    return n1*n2; 
} 

int operation(int op) { 
    // code that will call the method subtraction when I press 1. 
    // same for multiplication... 
} 

int main() { 
} 
+1

你問如何使用'if'語句? – 2014-10-26 14:49:33

+2

爲什麼不參加講座並學習這些東西? – 2014-10-26 14:49:49

+0

我想他在問如何使用'switch'語句。 – Westbrook 2014-10-26 14:50:24

回答

1
int operation(int op, int n1, int n2) { 
    switch(op) 
    { 
     case 1: 
      return subtraction(n1, n2); 

     case 2: 
      return multiplication(n1, n2); 

     default: 
      // default case, when the op value is neither 1 or 2 
      cout << "Error! << endl; 
      return 0; 
    } 
} 

@Edit:增加了默認的情況下,以下建議。另外,我認爲你應該讓你的變量名稱更具描述性。

+2

需要一個默認值,以防萬一 – 2014-10-26 14:53:52

+0

我想這就是我要找的。但它給了我一個與返回乘法相符的錯誤(int n1,int n2); //類型名稱是不允許的。在函數中調用的參數太少 – 2014-10-26 15:10:47

+1

默認值應返回值 – 2014-10-26 15:11:20