2017-03-01 33 views
1

所以我只是寫了一個簡單的計算器使用函數,我想盡可能容易使用。我基本上希望在1行代碼中可以完成詢問數字和計算以及計算結果的整個過程。但我有我的問題。在下面的代碼中,當我在主函數 「cout < < calculate(askCalculation(),askNumber1(),askNumber2())< < endl;」 和我運行該程序,然後我想它首先要求計算,然後第一個數字,然後第二個數字。但事實並非如此,實際上它是以excact的方式進行的。是有原因的,我該如何解決這個問題?C++:爲什麼它總是先做最後一個參數?

噢,請我知道你可以只把三問funtion在1類使其更加簡單,但有什麼辦法可以把計算funtion在同一個班?

#include <iostream> 

using namespace std; 

int calculate(int calculation, int firstNumber, int lastNumber) 
{ 
    switch(calculation) 
    { 
    case 1: 
     return firstNumber + lastNumber; 
     break; 
    case 2: 
     return firstNumber - lastNumber; 
     break; 
    case 3: 
     return firstNumber * lastNumber; 
     break; 
    case 4: 
     return firstNumber/lastNumber; 
     break; 
    } 
} 
int askNumber1() 
{ 
    int a; 
    cout << "Give the first number" << endl; 
    cin >> a; 
    return a; 
} 
    int askNumber2() 
{ 
    int b; 
    cout << "Give the second number" << endl; 
    cin >> b; 
    return b; 
} 
int askCalculation() 
{ 
    int c; 
    cout << "what calculation do you want to do? add (1) subtract (2) multiplication (3) divide (4)" << endl; 
    cin >> c; 
    return c; 
} 
int main() 
{ 
    cout << calculate(askCalculation(), askNumber1(), askNumber2()) << endl; 
    return 0; 
} 

回答

2

函數參數的求值順序未在C或C++中定義。如果您需要特定訂單,請按照需要的順序將這些函數的返回值分配給指定變量,然後將這些變量傳遞給該函數:

int a = askCalculation(); 
int b = askNumber1(); 
int c = askNumber2(); 
cout << calculate(a, b, c) << endl; 
相關問題