我正在尝试使用函数制作选秀节目类型的投票程序。
我已经弄清楚了其中的大部分内容。该程序会提示您输入一个名称,然后是五个分数,如果您键入“完成”而不是名称,它将关闭。我在大部分代码中使用函数来练习它们。
我的大问题是可能有无限多的名字(与用户输入的一样多),我不知道如何将每个名字的所有 5 个分数相加,我不知道如何区分它们。将 5 分取平均,平均数最高的人(3 分,下降 2 分)将获胜。
旁注:我需要去掉每个人的最高分和最低分,我相信我可以弄清楚,但是一个具有此功能的示例会对他们的新手有所帮助。
我对此进行了很多研究,但找不到任何与我足够相似的示例(可能有无限数量的参赛者。)
到目前为止,这是我的代码,底部的函数是我弄乱函数以掌握它们的窍门,看看我是否能从一个名字中得到任何分数的总和。
#include <iostream>
#include <string>
using namespace std;
void validCheck();
void calcAvgScore();
void findHigh();
void findLow();
int main(){
int judge = 1;
double score = 0;
string name;
while (name != "done" || name != "Done"){
cout << "Enter Contestant Name, if no more, type 'done': ";
cin >> name;
if (name == "done" || name == "Done"){ break; }
for (judge = 1; judge < 6; judge++){
cout << "Enter score " << judge << " ";
validCheck();
}
}
system("pause");
return 0;
}
void validCheck(){
double score;
cin >> score;
if (score < 1 || score > 10){
cout << "Please Enter a score between 1 and 10: ";
cin >> score;
}
}
void calcAvgCheck(){
double score = 0, value = 0;
static int average;
score += value
}
最佳答案
在 while 循环外声明一个字符串 "winner"、double "win_avg"、double "avg"。
让您的 validCheck() 返回作为输入给出的 double 值(命名分数)。
在 for 循环之前声明一个 double 组(double[5] 分数)。将从 validCheck() 返回的每个值存储到数组中)。
调用 std::sort(std::begin(scores), std::end(scores)) 对你的分数进行升序排序。求平均值(忽略最大值和最小值),并保留最大平均值以及具有最大平均值的人的姓名。
#include <algorithm> // std::sort
...
double validCheck();
...
int main(){
string name;
string winner;
double win_avg;
double avg;
while (name != "done" || name != "Done"){
cout << "Enter Contestant Name, if no more, type 'done': ";
cin >> name;
double scores[5];
if (name == "done" || name == "Done"){ break; }
for (int judge = 0; judge < 5; ++judge){
cout << "Enter score " << judge << " ";
scores[judge] = validCheck();
}
std::sort(std::begin(scores), std::end(scores));
for(int score = 1; score < 4; ++score)
avg += scores[score];
avg /= 3;
if(avg > win_avg) {
winner = name;
win_avg = avg;
}
avg = 0;
}
std::cout << "Winner is: " << winner << "\n";
}
double validCheck(){
double score;
cin >> score;
if (score < 1 || score > 10){
cout << "Please Enter a score between 1 and 10: ";
cin >> score;
}
return score;
}
如果你想在一个函数中找到平均值并返回你可以这样做的值
double calcAvgCheck(const double& scores[5]) {
double avg = 0.0;
for(int score = 1; score < 4; ++score)
avg += scores[score];
avg /= 3;
return avg;
}
关于c++ - 如何使用函数区分名称之间的分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593300/