如何将分数添加到它们对应的名称中

How to add scores to the names they correspond to

本文关键字:添加      更新时间:2023-10-16

我正在编写一个代码,该代码使用函数(而不是数组)来创建美国偶像风格的投票系统。我没有使用数组,因为我真的需要先掌握函数。

每位参赛者有5票,去掉最高和最低,平均最后3票得到答案,平均数最高的人获胜。但是,参赛者的数量基于用户输入(可能是无限数量的参赛者)

我不知道如何获得每个学生的平均值,仅作为质量,截至目前,我的程序仅将最后的输入值作为获胜者。这是我的代码。

如果有任何关于如何为不同参赛者获得不同平均值的帮助,请告诉我,我是函数新手,对 c++ 也很陌生

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void validCheck();
void calcAvgCheck();
void findHigh();
void findLow();
ofstream outputFile;
ofstream inputFile;
double totalScore, average, score;
string name;
int main(){
    int judge = 1;
    outputFile.open("contestant.txt");
    while (name != "done" || name != "Done"){
        cout << "Enter Contestant Name, if no more, type 'done': ";
        cin >> name;
        outputFile << name << " ";
        if (name == "done" || name == "Done"){ break; }
        for (judge = 1; judge < 6; judge++){
            cout << "Enter score " << judge << " ";
            validCheck();
            outputFile << " " << score << " ";
            calcAvgCheck();
        }
    }
    cout << "Winner is: " << name << "with a score of: " << average;
    system("pause");
    return 0;
}
void validCheck(){
    cin >> score;
    if (score < 1 || score > 10){
        cout << "Please Enter a score between 1 and 10: ";
        cin >> score;
    }
    totalScore += score;
}
void calcAvgCheck(){
    inputFile.open("contestant.txt");
    average = totalScore / 5;
}

函数calcAvgCheck();应该在外部调用 for 循环。

您可以将分数保存在向量中,并可以重复使用以计算平均值,如下所示。

请注意,定义全局值不是一个好的做法。我知道还有更多的工作需要,这应该是你的功课。请从这里开始,如果您还有其他问题,请发布一个不同的问题作为本问题的延续。

#include <iostream>
#include <string>
#include<vector>

using namespace std;
void validCheck();
double calcAvgCheck(std::vector<int>& scores);
void findHigh();
void findLow();

double totalScore, score;
string name;
int main(){
    int judge = 1;
    vector<int> scores;
    double  average =0.0;
    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();
            scores.push_back(score);
        }
        average =calcAvgCheck(scores);
        std::cout<< " average:"<< average<<"n";
    }
    cout << "Winner is: " << name << "with a score of: " << average;
    system("pause");
    return 0;
}
void validCheck(){
    cin >> score;
    if (score < 1 || score > 10){
        cout << "Please Enter a score between 1 and 10: ";
        cin >> score;
    }
    totalScore += score;
}
double  calcAvgCheck( std::vector<int>& scores)
 {
        int sum=0;
        for(auto &x : scores)
           sum+=x;
        return sum/scores.size();
 }