2011-11-01 66 views
0

我想知道如何使用void函數輸出基於條件的結果。我正在嘗試創建一個Windchill計算器。如何在C++中操作函數根據條件輸出不同的結果?

我可以添加什麼使下面的程序輸出的氣溫低於4.8kph的速度? 我可以做些什麼來使print_result無效,以便打印各種語句 - 比如-20至-30°的windchill(WC)的「wear 3 layers」或者-30 to -40的wear 5 layers?感謝那些能夠幫助的人!

#include <iostream> 
#include <cmath> 
using namespace std; 

bool is_cold(double V) 
{ 
    bool is_windy; 
    if (V <= 4.8) 
    { 
     is_windy = false; 
    } 
    else 
     is_windy = true; 
    return (is_windy); 
} 
int windchill_index(double T, double V) 
{ 
    int WC; 
    WC = 13.12 + 0.6215*T - 11.37*pow(V,0.16) + 0.3965*T*pow(V, 0.16); 
    return (WC); 
} 
void print_result(double WC) 
{ 
    cout << "From the input for tempearature and wind speed, the wind chill is: "<< WC << endl; 
} 

int main() 
{ 
    double WC = 0, T = 0, V = 0; 
    bool is_windy = false; 
    if (!is_windy) 
     { 
      cout << "Please enter the air temperature in Celsius followed by the windpseed in kph: " << endl; 
      cin >> T; 
      cin >> V; 

      is_windy = is_cold(V); 
     } 
    WC = windchill_index(T, V); 

    print_result (WC); 
    return 0; 
} 
+10

嗯...'if'報表? –

回答

0

你熟悉布爾邏輯運算符and(& &)和or(||)?還要確保在邊界條件(-20,-30,-40)下進行測試,以確保獲得您想要的結果!

void print_result(double WC) 
{ 
    cout << "From the input for tempearature and wind speed, the wind chill is: "<< WC << endl; 
    if (WC <= -20 && WC > -30) { 
     cout << "Wear 3 layers!" << endl; 
    } else if (WC <= -30 && WC > -40) { 
     cout << "Wear 5 layers!" << endl; 
    } else { 
     cout << "Wear ALL the layers!" << endl; 
    } 
} 

編輯::要回答的評論你的問題:

int main() 
{ 
    double WC = 0, T = 0, V = 0; 
    bool is_windy = false; 
    if (!is_windy) 
     { 
      cout << "Please enter the air temperature in Celsius followed by the windpseed in kph: " << endl; 
      cin >> T; 
      cin >> V; 

      is_windy = is_cold(V); 
     } 
    //If its windy we want to calculate the windchill index, otherwise just use the ambient temp 
    if (is_windy) { 
     WC = windchill_index(T, V); 
    } else { 
     WC = T 
    } 

    print_result (WC); 
    return 0; 
} 
+0

謝謝!沒有考慮在函數中嵌套一個if-else ...(不知道你能做到這一點!) –

+0

你還會知道如何修改原始函數中的代碼,使得在4.8以下的風速下,溫度輸入T是風冷,WC?試圖在這種情況下使用bool邏輯沒有成功。 –

+0

我已經爲你更新了我的答案。 – Grambot

相關問題