贏家所以在我的編程類的實驗室,有人問我這個問題:「寫的是提示用戶名和兩個籃球隊的點數然後用一個程序,它使用了嵌套,如果顯示的贏家(如有)或一條消息,說明平局,如果兩隊有相同數量的點 - 每個場景中的一個屏幕截圖 - 用一個函數來確定可能的方案「的功能更有效地利用它確定用戶輸入
。我得到了答案,但我覺得它可以大大簡化,我放入函數的唯一原因是因爲它是必需的。我希望得到一些關於如何使這個函數對未來的代碼更有效和更有用的幫助。任何提示將不勝感激! (下面的代碼)
#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
}
似乎瘋了,使用'if'語句做一個比較分數的函數,然後必須使用另一個'if'語句來解碼它的結果 – harmic
Off topic:不是用幻數值返回一個int,考慮一下'enum result {TEAM1,TEAM2,TIE};'。像這樣的小程序不是那麼有用,但是編譯器可以進行額外的檢查,以確保沒有人做任何傻事,它是從來都不會太早進入良好的生活習慣。 – user4581301
這裏使用一個功能的好地方是輸入驗證,以確保用戶輸入好的分數。目前,程序可以通過用戶輸入諸如「fubar」而不是諸如負數或pi之類的數字或無意義值到百位小數點來打亂。 – user4581301