无法在数组C ++中找到最高/最低元素

时间:2014-02-17 23:29:50

标签: c++ arrays function

我对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;
}

3 个答案:

答案 0 :(得分:6)

这是因为getJudgeData按值double score获取。结果,最终用户的条目仍然局限于getJudgeData函数;传递给函数的judgeScores[i]变量保持不变。

添加&符号以解决此问题:

void getJudgeData(double &score) {
    ...
}

现在参数通过引用传递,让getJudgeData对其进行修改。

答案 1 :(得分:4)

更改

void getJudgeData(double score)

void getJudgeData(double &score)

答案 2 :(得分:2)

看起来您的大多数逻辑都没问题,除非您在calcScore()中交换了作业。你有:

scores[i] = newScore[j];

你可能意味着:

newScore[j] = scores[i];

另外,要小心:如果您的输入数组包含多个等于最小值或最大值的分数,则删除它们后剩余的分数将少于3个。

编辑:哦,是的,以及其他人所说的关于通过引用getJudgeData()来传递价值的内容。