Различные расчеты по GPA с использованием коллекции студентов и их соответствующих GPA - PullRequest
0 голосов
/ 28 марта 2020

Чтобы дать гораздо больше подробностей по вопросу, над которым я работаю, вот точное задание:

Напишите программу, которая рассчитывает средний, минимальный, максимальный и средний средний балл для всех студентов. Во-первых, ваша программа будет читать записи о студентах (имена и GPA) и определять количество записей о студентах в файле. После того, как все имена и GPA будут получены, ваша программа будет сортировать студенческие GPA и имена в порядке возрастания GPA. Наконец, ваша программа: 1) отобразит все имена и средний балл, 2) определит и отобразит минимальный и максимальный средний балл (с соответствующими именами учащихся) и 3) вычислит и отобразит средний средний балл.

Вот что я имею в качестве готового продукта:

//gpaCalc.cc                                                                                                                                                                                   
//Author: O'Brien Little                                                                                                                                                                       
//Purpose: To calculate and display the average, minimum and maximum GPA for some U of L students, where the GPA's and student names are read from
//an input file and are stored as arrays 
//Inputs: GPA's of several students, student names                                                                                                                                                          
//Outputs: Average, minimum and maximum GPA of the collection of students, along with the corresponding student names
//and display a list of all students and their respective GPA's
//Assumptions: Max 50 Students' information

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

const int arraySize=50; //Upper limit on the number of students and GPA's

//Function prototypes
void obtainNamesAndGPAs(double GPA[], string name[], int &students);
void sortGPA(double GPA[], string name[], int students);
void displayMinMaxGPA(const double GPA[], const string name[], int students);
double calcAvgGPA(const double GPA[], int students);



int main()
{
    //Variable declarations
    double AvgGPA;
    int index=0, students;

    //Reading the names of the students and their corresponding GPAs and storing them in an array
    obtainNamesAndGPAs;

    //Sorting the students GPAs in assending order allong with the corresponding student names
    sortGPA;

    //Displaying all the names of the students and their GPAs
    cout << "Here is a list of all the students and their GPAs that were entered into te system: " << endl;

    //While loop to display all the students and their GPAs
    while(index<students)
    {
        cout << name[index] << GPA[index];
        index++;
    }

    //Displaying the lowest and the highest GPAs and the students that achieved those
    displayMinMaxGPA;

    //Calculating the average GPA of the collection
    AvgGPA = calcAvgGPA;

    //Displaying the average GPA to the user
    cout << "The average GPA of the collection of students was: " << AvgGPA << endl;

    //End program
    return 0;
}

//****************************************************************                                                                                                                             
//Function: obtainNamesAndGPAs                                                                                                                                                                        
//Purpose: To obtain the names and GPAs of the students                                                                                                                                
//Input: GPA[], name[], &students                                                                                                                                                             
//Return Value: Void                                                                                                                                                                           
//Assumtions: None                                                                                                                                            
//****************************************************************  
void obtainNamesAndGPAs(double GPA[], string name[], int &students)
{
    //Array access variable
    int indexn=0, indexg=0; 

    //File stream declaration
    ifstream inFile;

    //Opening the input file and read in the first value
    inFile.open("GPA.txt");
    inFile >> name[indexn];

    //While loop to gather the GPAs from the file and insert them into their corresponding array index
    while(!inFile.eof() && indexn < arraySize)
    {
        indexn++;
        inFile >> GPA[indexg];
        indexg++;
        inFile >> name[indexn];
        students++;
    }
    //End of function
    return;
}

//****************************************************************                                                                                                                             
//Function: sortGPA                                                                                                                                                                       
//Purpose: To sort students (and thier corresponding GPAs 
//in assending order
//Input: GPA[], name[], students                                                                                                                                                            
//Return Value: Void                                                                                                                                                                           
//Assumtions: None                                                                                                                                            
//****************************************************************  
void sortGPA(double GPA[], string name[], int students)
{
    //Variable declarations
    double temporaryg;
    int first, second;
    string temporaryn;

    //Sorting the GPAs by asscending order
    //For loop to indicate the first value of the GPA array
    for(first=0;first<students;first++)
    {       
        //For loop to indicate the following value in the GPA array to check 
        for(second=first+1;second<students;second++)
        {
            //If statement to make sure the GPA and name array are in asscending order and 
            //ensures the student name stays with the GPA
            if(GPA[first]>GPA[second])
            {
                //Storing the bigger GPA and name for later
                temporaryg=GPA[first];
                temporaryn=name[first];
                //Making it so the smaller GPA and name comes first
                GPA[first]=GPA[second];
                name[first]=name[second];
                //Making the lower GPA and name come second
                GPA[second]=temporaryg;
                name[second]=temporaryn;
            }
        }
    }

    //End of function
    return;
}

//****************************************************************                                                                                                                             
//Function: displayMinMaxGPA                                                                                                                                                                      
//Purpose: To display the Min and Max GPA and their students
//Input: GPA[], name[], students                                                                                                                                                            
//Return Value: Void                                                                                                                                                                           
//Assumtions: None                                                                                                                                            
//**************************************************************** 
void displayMinMaxGPA(const double GPA[], const string name[], int students)
{
    //Variable declaration
    //initialized to extreme values to ensure they will be taken by the array values
    double Maxg=0, Ming=10;
    int index;
    string Maxn, Minn;

    //For loop to find the Max and Min GPA in the array and find the corresponding 
    //students name
    for(index=0;index<students;index++)
    {
        if(GPA[index]>Maxg)
        {
            Maxg=GPA[index];
            Maxn=name[index];
        }
        else if(GPA[index]<Ming)
        {
            Ming=GPA[index];
            Minn=name[index];
        }
        else
        {
            break;
        }
    }

    //Displaying the Min and Max GPA and the corresponding students to the user
    cout << "The minimum GPA that was entered belonged to: " << Ming << " and was: " << Minn << endl;
    cout << "The maximum GPA that was entered belonged to: " << Maxg << " and was: " << Maxg << endl;

    //End of function
    return;
}

//****************************************************************                                                                                                                             
//Function: calcAvgGPA                                                                                                                                                                   
//Purpose: To calculate the average GPA
//Input: GPA[], students                                                                                                                                                            
//Return Value: AvgGPA                                                                                                                                                                           
//Assumtions: None                                                                                                                                            
//**************************************************************** 
double calcAvgGPA(const double GPA[], int students)
{
    //Variable declarations
    double sum, AvgGPA;
    //Index set to zero to make sure the array starts in the first position
    int index=0;

    //While loop to take each individual GPA out of the array and add it to sum
    while(index<students)
    {
        sum = sum + GPA[index];
        index++;
    }

    //Calculating the average GPA
    AvgGPA = sum/students;


    //End of function and return AvgGPA
    return AvgGPA;
}

Однако я получаю следующие ошибки, но не могу решить их самостоятельно:

В функции 'int main ()':

  • 32: 23: предупреждение: оператор является ссылкой, а не вызовом функции 'receiveNamesAndGPAs' [-Waddress] Решено`
  • 32: 23: предупреждение: оператор не действует [-Wunused-value] Решено`
  • 35: 12: предупреждение: оператор является ссылкой, а не вызовом функции sortGPA [-Waddress] Solved`
  • 35: 12: предупреждение: оператор не действует [-Wunused-value] Решено`
  • 43: 17: ошибка: 'имя' не было объявлено в этой области
  • 43: 32: ошибка: 'GPA' не было объявлено в этой области
  • 48: 21: предупреждение: оператор не действует [ -Wunused-value] Решено`
  • 51: 12: ошибка: невозможно преобразовать 'double (const double *, int)' в 'double' в присваивании Solved``

Любая помощь будет принята с благодарностью, заранее спасибо

"` "ошибки были решены путем вызова функции и установки параметров в

"` `" ошибки были устранены путем помещения параметров в скобки после вызова функции calcAvgGPA

1 Ответ

0 голосов
/ 28 марта 2020

У вас есть несколько больших ошибок в понимании основ c. Давайте через них 1049 * и посмотрим, чем мы можем помочь просветить. Кроме того, вы используете std :: string, но не используете std::vector (что облегчит это общее назначение).

Также (2) заявление об отказе , я не смотрел на logi c в любой из функций, чтобы увидеть, будут ли они работать правильно ... как только это будет сделано для вас, вы можете поработать над получением правильного logi c, если он неправильный.

  1. Исправьте ошибки, о которых упоминает CoryKramer (которые вы отредактировали, чтобы предложить, что у вас есть)
  2. вы не объявляете GPA или называете объекты в основной функции
    • Поскольку вы не используя классы и не имея данных об элементах, вам необходимо сохранить эту информацию в области main.
  3. Ваши функции не принимают ссылки на их параметры, вы их берете по копии

Не объявлять переменные

    //Displaying all the names of the students and their GPAs
    cout << "Here is a list of all the students and their GPAs that were entered into te system: " << endl;

    //While loop to display all the students and their GPAs
    while(index<students)
    {
        cout << name[index] << GPA[index];  // <--- This line
        index++;
    }

Вышеупомянутая строка пытается ссылаться на 2 переменные, которые не существуют в этой области (или глобальной области). Вам необходимо объявить эти переменные в области действия main. Если у вас нет этих переменных в области видимости, где они могут быть отредактированы, различные функции не смогут обрабатывать одни и те же переменные.


Получение элементов по копии вместо ссылки

//Function prototypes
void obtainNamesAndGPAs(double GPA[], string name[], int &students);

В этом прототипе вы берете параметр students по ссылке, что означает, что переменная в области видимости main может быть обновлена. Но вы не принимаете какие-либо другие параметры по ссылке, а по копии. Обратите внимание на отсутствующий &? Даже если бы у вас были эти переменные в области действия main, они не были бы обновлены, поскольку функции делают копии и используют эти копии в своих областях вместо изменения переменной в более высокой области действия. Все ваши функции по существу имеют эту ошибку. Подумайте о том, что нужно функциям для ввода и какие переменные нужно изменить, а какие нет.


Также

У меня такое чувство, что вы столкнетесь с большими проблемами с динамическими c размерами массива. Я вижу это, потому что я не вижу new экземпляров для GPA или name переменных. Это где std::vector действительно будет сиять, но я оставлю это на ваше усмотрение (поскольку это домашнее задание).

...