0

那作业:

在体操或跳水比赛中,每个参赛者的分数是通过去掉最低和最高分数然后将剩余分数相加来计算的。评委打分在 1 到 10 之间,1 分最低,10 分最高。编写一个程序,从输入文件中读取评委的分数(分数在 5 到 10 之间),并输出参赛者收到的分数,格式为小数点后两位。例如,输入文件包含:9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8 下降分数:9.0 和 9.9 获得的分数:56.90 由于您不知道分数的确切数量,因此您需要在从输入文件中读取分数时计算分数并将其用作实际大小或实际存储在数组中的元素数量。您应该参考讲义以获取有关如何从文件中读取数据的更多信息,

我的代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cassert>

using namespace std;

void OpenFile(ifstream &ScoresFile);
void GetScores(ifstream &ScoresFile, double Scores[], int &size);
void MinMax(double Scores[], int size);

int main()
{
    ifstream ScoresFile;
    double Scores[10];
    int size;

    OpenFile(ScoresFile);
    GetScores(ScoresFile, Scores, size);
    MinMax(Scores, size);

    return(0);
}

// This function will prompt the user to name the input file that will store the scores.
void OpenFile(ifstream &ScoresFile)
{
    string infilename;

    cout << "Please enter the name of your input file: ";
    cin >> infilename;

    ScoresFile.open(infilename.c_str());
    assert(ScoresFile);
}

// This function will get the scores from the file and store them in an array.
void GetScores(ifstream &ScoresFile, double Scores[], int &size)
{
    int i = 0;

    do
    {
        ScoresFile >> Scores[i];
        i++;
    }
    while(ScoresFile);

    size = i;
}

// This function will figure out the minimum and maximum scores, and remove them from the array.
void MinMax(double Scores[], int size)
{
    double minScore = Scores[0];
    double maxScore = Scores[0];
    double points = 0;  
    int i;

    for(i = 0; i < 10; i++)     
    {
        points += Scores[i];
        if (Scores[i] > maxScore)
            maxScore = Scores[i];
        if (Scores[i] < minScore)
            minScore = Scores[i];
    }

    points = (Scores[i] - minScore - maxScore);

    cout << fixed << showpoint << setprecision(1) << points << endl;
}

我的问题: 所以它接受文件信息(我从作业中复制了相同的数字并将它们放在一个文本文件中),它把它放入数组中。它计算 minScore 和 maxScore (我相信......已经对其进行了测试并且它工作,以及额外的垃圾代码,我相信这是数组重载)。我需要做的是从等式中删除 minScore 和 maxScore,然后将剩余的数字相加以创建总分,并将其输出到屏幕上。我被困在那个部分。当我按原样运行代码时,我得到-9.9的输出。

任何帮助/推动正确的方向,我都非常感谢。请不要使用超级花哨的高级编码——项目所说的正是老师想要的。:-) 另外我不明白,呵呵...

4

1 回答 1

0

在您的 MinMax 函数中

points = (Scores[i] - minScore - maxScore);

i 的值在这里是 10,因此您试图访问越界数组。

相反,您可能想要这样做:

points -= minScore + maxScore;
于 2013-10-25T14:09:00.800 回答