2016-11-03 40 views
1

贏家所以在我的編程類的實驗室,有人問我這個問題:「寫的是提示用戶名和兩個籃球隊的點數然後用一個程序,它使用了嵌套,如果顯示的贏家(如有)或一條消息,說明平局,如果兩隊有相同數量的點 - 每個場景中的一個屏幕截圖 - 用一個函數來確定可能的方案「的功能更有效地利用它確定用戶輸入

。我得到了答案,但我覺得它可以大大簡化,我放入函數的唯一原因是因爲它是必需的。我希望得到一些關於如何使這個函數對未來的代碼更有效和更有用的幫助。任何提示將不勝感激! (下面的代碼)

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

string bballTeam1; 
string bballTeam2; 
int scoreCheck(int, int); 


int main() { 

int winner; 
int score1 = 0; 
int score2 = 0; 

cout << "Enter a basketball team name: "; 
getline(cin, bballTeam1); //had to make sure to account for spaces 
cout << endl; 
cout << "Enter a basketball team name: "; 
getline(cin, bballTeam2); //had to make sure to account for spaces 
cout << endl; 

cout << "How many points do the " << bballTeam1 << " have? "; 
cin >> score1; //get points 
cout << endl; 
cout << "How many points do the " << bballTeam2 << " have? "; 
cin >> score2; //get points 
cout << endl; 

winner = scoreCheck(score1, score2); // go to function 

if(winner == 1) { //if statements to determine correct output 
    cout << "The " << bballTeam1 << " are winning!" << endl; 
} 
else if(winner == 2) { 
    cout << "The " << bballTeam2 << " are winning!" << endl; 
} 
else { 
    cout << "Looks like they are tied up!" << endl; 
} 

return 0; 
} 
int scoreCheck(int a, int b) { //a is score1, b is score2 

int winner; //set value to int for output 

if (a > b) { 
    winner = 1; //1 is team 1 
} 
else if(a < b) { 
    winner = 2; //2 is team 2 
} 
else if(a == b) { 
    winner = 0; //0 is tie 
} 

return winner; //returns value of winner 
} 
+0

似乎瘋了,使用'if'語句做一個比較分數的函數,然後必須使用另一個'if'語句來解碼它的結果 – harmic

+0

Off topic:不是用幻數值返回一個int,考慮一下'enum result {TEAM1,TEAM2,TIE};'。像這樣的小程序不是那麼有用,但是編譯器可以進行額外的檢查,以確保沒有人做任何傻事,它是從來都不會太早進入良好的生活習慣。 – user4581301

+0

這裏使用一個功能的好地方是輸入驗證,以確保用戶輸入好的分數。目前,程序可以通過用戶輸入諸如「fubar」而不是諸如負數或pi之類的數字或無意義值到百位小數點來打亂。 – user4581301

回答

0

當坐下來寫一個函數,第一件事想到的是該函數的最好的接口之一:什麼樣的價值觀會拿的,會是什麼返回。

的一些因素在這裏考慮的是功能,可用輸入的目的,和功能將被如何使用。

在你的情況,你已經創建了一個函數,它接受兩個整數作爲輸入,對它們執行一些很簡單的邏輯,並返回一個與特殊值編碼來表示結果的另一個整數。雖然這是有效的並且有效,但在您使用的用例中很尷尬:在調用函數後,您需要使用非常相似的邏輯來處理結果。

我會更傾向於使函數返回的代表將比分檢驗的結果,像這樣的字符串:

string scoreCheck(int score1, string team1, int score2, string team2) { 

    string result; 

    if (score1 > score2) { 
     result = "The "+team1+" are winning!"; 
    } 
    else if(score1 < score2) { 
     result = "The "+team2+" are winning!"; 
    } 
    else { 
     result = "Looks like they are tied up!"; 
    } 

    return result; 
} 

然後,您可以簡化您的主要功能,更換全部的if/then與此分支:

cout << scoreCheck(score1, bballTeam1, score2, bballTeam2) << endl; 

這一切都歸結到功能如何將使用 - 在這種情況下,我們從功能上要的是代表遊戲,我們可以直接輸出結果的字符串。這個函數沒有被用在程序中的任何其他上下文中,所以我們應該儘可能地使它適合這個用例。

另外請注意,我改變了嵌套的最後一部分,如果以一個普通的「其他」 - 有沒有必要檢查score1 == score2因爲我們已經消滅的其他情形。