更有效地使用根据用户输入决定获胜者的函数

More efficient use for a function that determines winner on user input

本文关键字:决定 输入 获胜者 函数 用户 有效地      更新时间:2023-10-16

在我的编程课实验中,有人问我这个问题:"写一个程序,提示用户输入两个篮球队的名字和得分。然后,它使用一个嵌套的if来显示获胜者(如果有的话),或者如果两个队的得分相同,则显示平局的消息——每个场景一个屏幕截图——使用一个函数来确定可能的场景。"

我得到了答案,但我觉得它可以大大浓缩,我放一个函数的唯一原因是因为它是必需的。我想要一些关于如何使这个函数更有效和有用的未来代码的帮助。任何提示将非常感激!(下面的代码)

#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
}

在编写函数时,首先要考虑的是函数的最佳接口:取什么值,返回什么值。

这里需要考虑的因素包括函数的目的、可用的输入以及如何使用函数。

在你的例子中,你已经创建了一个函数,它接受两个整数作为输入,对它们执行一些非常简单的逻辑,并返回另一个用特殊值编码的整数来表示结果。虽然这是有效的和工作的,但在你把它放在用例中是尴尬的:在调用函数之后,你需要立即使用非常相似的逻辑来处理结果。

我更倾向于让函数返回一个表示分数检查结果的字符串,如下所示:
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; 

这一切都归结为函数的使用方式——在这种情况下,我们想从函数中得到的是一个可以直接输出的表示游戏结果的字符串。该函数没有在程序的任何其他上下文中使用,所以我们应该使它尽可能适合这个用例。

还请注意,我将嵌套if的最后一部分更改为普通的'else'—不需要检查score1 == score2,因为我们已经消除了其他情况。