不计算程序中的最低和最高成绩。(C++)(流)

Doesn't calculate min and max grades in program. (c++) (fstream)

本文关键字:C++ 高成绩 计算程序      更新时间:2023-10-16

该程序的重点是打开并阅读一个文本文件,其中包含学生的学术代码 -> AEM 和他/她的总体成绩。然后,如果特定学生的成绩大于 5,它将在名为 success 的文本上写下他/她的学术代码,以及成绩等。我的问题是它正确计算了这 5 名学生的平均成绩,但没有计算最高和最低成绩。当我运行程序时,出现的窗口显示课程的正确平均值,但是最大和最小成绩始终为 0。谁能帮我?可能我没有以正确的方式比较它们。

#include <iostream>
#include <fstream>
using namespace std;
const int arraySize = 5;
int main(int argc, char** argv)
{
    ifstream d;
    d.open("students.txt");
    ofstream b;
    b.open("succesful.txt");
    ofstream c;
    c.open("unsuccesful.txt");
    int aem;
    double a[arraySize];
    int min, max;
    double grades, average;
    grades = average = 0;
    min = max = 0;
    for (int i = 0; i < arraySize; i++)
    {
        d >> aem >> a[i];
        grades = grades + a[i];
        average = grades / arraySize;
        if (a[i] >= 5) b << aem << " " << a[i] << endl;
        else c << aem << " " << a[i] << endl;
    }
    for (int i = 0; i < arraySize; i++)
    {
        if (a[i] = max)
            max = a[i];
        break;
        if (a[i] = min)
            min = a[i];
        break;
    }

    cout << "The average is:" << average;
    cout << "Maximum is:" << max;
    cout << "Minimum is:" << min;
    d.close(); c.close(); b.close();
    system("pause");
    return 0;
}
int main(int argc, char** argv)
没有必要

argcargv来到这里。它可以只是int main().

int min, max;
double grades, average;
grades = average = 0;
min = max = 0;

在声明后分配值是不必要的且效率低下。此外,0是一个整数,而不是浮点数。您可以初始化它们:int min = 0, max = 0; double grades = .0, average = .0;

grades = grades + a[i];

可以缩短为grades += a[i];

average = grades / arraySize;

这句话毫无意义地存在于 for 循环中。您可以在循环后执行此操作。

for (int i = 1; i < arraySize; i++) {

你忘记了a的第零个元素. 必须更换int i = 1;才能int i = 0;

if (i >= max)
    max = i; 
if (i <= min)
    min = i;

你把a[i]误认为是i.如果a[i]max已经相等,则无需将a[i]分配给max.它们可以只是:

if (a[i] > max)
    max = a[i]; 
if (a[i] < min)
    min = a[i];

system("pause");

std::system取决于系统环境,并且可能会发生意外行为。应将其替换为:

std::cout << "Press enter key." << std::endl;
std::cin.get();