更有效地使用根据用户输入决定获胜者的函数
More efficient use for a function that determines winner on user input
在我的编程课实验中,有人问我这个问题:"写一个程序,提示用户输入两个篮球队的名字和得分。然后,它使用一个嵌套的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,因为我们已经消除了其他情况。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如果我决定输入 (1 2) 而它要求 x,为什么我的输出会出错,但如果我输入 (12) 工作正常
- 有没有一种优雅的方法,根据用户输入只决定一次
- C++模板:重载运算符+,而返回类型由输入类型决定
- 更有效地使用根据用户输入决定获胜者的函数
- 从输入文件的最后一列决定一个例程