我對C++很陌生,只有C#,Python和JS的經驗,所以對我很有幫助!查找數組C++中最高/最低元素的問題
我將用戶輸入的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;
}
除了一切,你將有一些問題,如果有人提出在以同樣的比分多次,它正好是最高或最低得分了。 –
嘗試使用矢量,對矢量進行排序,刪除最高和最低的元素(第一個和最後一個)。 :-) –