【发布时间】:2014-02-17 23:29:50
【问题描述】:
我对 C++ 很陌生,只有 C#、Python 和 JS 方面的经验,所以请多多包涵!
我将用户输入的 5 个分数存储在一个数组中。我传递数组并评估数组中的分数以找到最小值和最大值。我需要去掉这两个,然后找到其他 3 个值的平均值。我的问题是,我没有找到最高/最低值。我在 findLowest() 和 findHighest() 中有逻辑,但为了测试它,我在 main() 中放置了相同的逻辑,以查看它是否在它通过之前工作,并且它不工作。有人可以指导我找到数组中的最高/最低值吗?谢谢!
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;
void getJudgeData(double score)
{
cin >> score;
if (score > 10 || score < 0)
{
cout << "Invalid score, please enter again." << endl;
cin >> score;
}
else
{
cout << "Thank you." << endl;
}
}
double findLowest(double scores[])
{
double lowScore = *min_element(scores, scores+5);
return lowScore;
}
double findHighest(double scores[])
{
double highScore = *max_element(scores, scores+5);
return highScore;
}
double calcScore(double scores[])
{
double finalScore;
double sum = 0;
double newScore[3] = {};
double lowScore = findLowest(scores);
double highScore = findHighest(scores);
int j = 0;
for (int i=0; i < 5; i++)
{
if (scores[i] != lowScore && scores[i] != highScore)
{
scores[i] = newScore[j];
j++;
}
}
for (int k=0; k < 3; k++)
{
sum = sum + newScore[k];
}
finalScore = sum/3;
return finalScore;
}
int main()
{
double finalScore;
double judgeScores[5] = {};
for (int i = 0; i < 5; ++i)
{
cout << "Enter judge " << i + 1 << "'s score: ";
getJudgeData(judgeScores[i]);
}
finalScore = calcScore(judgeScores);
cout << "Highest score is: " << *max_element(judgeScores, judgeScores+5) << endl;
cout << "The final score is: " << finalScore << endl;
// This prevents the Console Window from closing during debug mode
cin.ignore(cin.rdbuf()->in_avail());
cout << "\nPress only the 'Enter' key to exit program: ";
cin.get();
return 0;
}
【问题讨论】:
-
除此之外,如果有人多次输入相同的分数并且恰好是最高或最低分数,您将会遇到一些问题。
-
尝试使用向量,对向量进行排序,删除最高和最低的元素(第一个和最后一个)。 :-)