gpt4 book ai didi

c++ - 如何给对应的名字加分

转载 作者:太空宇宙 更新时间:2023-11-04 13:35:58 24 4
gpt4 key购买 nike

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

每名参赛者有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 循环。

您可以将分数保存在一个 vector 中,并可以重新用于计算 avg,如下所示。

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

#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();
}

关于c++ - 如何给对应的名字加分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29597364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com