2016-12-08 5 views
-4

Моя структура массива не будет печататься правильно. Может кто-нибудь, пожалуйста, помогите мне? «Я должен напечатать структуру массива данных оценок учащихся. Код, похоже, работает, но я не знаю, что происходит, когда он печатает массив. И похоже, что функция calcAvg по какой-то причине не работает должным образом.Строка массива неправильно напечатана

Код:

#include <iostream> 
    #include <fstream> 
    #include <cctype> 
    #include <cstring> 
    #include <iomanip> 

    using namespace std; 

    double calcAvg(double [][6], int); 
    double calcLow(double [][6], int); 
    double calcHigh(double [][6], int); 

    struct studInfo{ 
     char fname[10]; 
     char lname[10]; 
     double low; 
     double high; 
     double average; 
    }; 

    int main() { 


     ifstream input; 
     ifstream input2; 
     double scores [9][6]; 
     char firstName[10]; 
     char lastName[10]; 
     int count = 0; 


     struct studInfo students[9]; 

     input.open("cis_testGrades.txt"); 

     while (!input.eof()){ 
      for(int a = 0; a < 9; a++){ 
       cout << "Student " << a+1 << ": "; 
       for(int b = 0; b < 6; b++){ 
        input >> scores[a][b]; 
        cout << scores[a][b] << " "; 
       } 
       cout << " " << endl; 
      } 
     } 
     input.close(); 

     /*cout << calcAvg(scores, 9) << endl; 
     cout << calcHigh(scores, 9) << endl; 
     cout << calcLow(scores, 9) << endl;*/ 

     input2.open("cis_students.txt"); 

     while (!input2.eof()){ 

      input2 >> firstName; 
      //firstName >> students[count].fname; 
      strcpy(students[count].fname, firstName); 

      input2 >> lastName; 
      //lastName >> students[count].lname; 
      strcpy(students[count].lname, lastName); 

      students[count].low = calcLow(scores, count); 

      students[count].high = calcHigh(scores, count); 

      students[count].average = calcAvg(scores, count); 

      count++; 

     } 

     input2.close(); 

     for(int a = 0; a < 9; a++) 
      cout << students[a].fname << " " << students[a].lname << " " << students[a].low << " " << students[a].high << " " << students[a].average << endl; 

     return 0; 
    } 

    double calcAvg(double grades[9][6], int student){ 

     double average; 
     double sum; 

     for(int a = 0; a < 6; a++) 
      sum += grades[student][a]; 

     average = sum/6; 

     return average; 


    } 

    double calcHigh (double grades[][6], int student){ 

     double high = 0; 

     for(int a = 0; a < 6; a++) { 
      if (grades[student-1][a] >= high) 
       high = grades[student-1][a]; 
     } 

     return high; 

    } 

    double calcLow (double grades[][6], int student){ 

     double low = 100; 

     for(int a = 0; a < 6; a++) { 
      if (grades[student-1][a] <= low) 
       low = grades[student-1][a]; 
     } 

     return low; 

    } 

cis_TestGrades.txt:

99 86 88 89 85 78 73 74 72 61 62 63 57 58 93 97 81 81 85 79 75 72 73 64 66 69 68 59 54 49 95 92 98 89 
87 83 71 70 76 65 60 61 84 82 81 80 77 73 74 78 70 71 72 79 

cis_students.txt:

Robert Smallwood 
Mary Stevens 
Sally Moore 
John Perkins 
Connor Cousins 
William Laws 
Renee Rivers 
Thomas Carver 
Donna Smith 

Выход:

Student 1: 99 86 88 89 85 78 
Student 2: 73 74 72 61 62 63 
Student 3: 57 58 93 97 81 81 
Student 4: 85 79 75 72 73 64 
Student 5: 66 69 68 59 54 49 
Student 6: 95 92 98 89 87 83 
Student 7: 71 70 76 65 60 61 
Student 8: 84 82 81 80 77 73 
Student 9: 74 78 70 71 72 79 
Robert Smallwood 6.32404e-322 5.96342e+228 9.93903e+227 
Mary Stevens 78 99 84 
Sally Moore 61 74 90.1667 
John Perkins 57 97 90.8333 
Connor Cousins 64 85 75 
William Laws 49 69 102.167 
Renee Rivers 83 98 83.5 
Thomas Carver 60 76 92.1667 
Donna Smith 73 84 88 
+0

Пожалуйста [править] Ваш вопрос, чтобы обеспечить [mcve]. –

+1

Off topic: [Почему iostream :: eof внутри условия цикла считается неправильным?] (Http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301

ответ

0

В каждой функции вы начинаете с массива [-1], а в C/C++ вы не получите исключения, она просто возьмет то, что находится в памяти перед массивом.

Change [студент-1] до [студента] и инициализируется сумму до 0.

Рекомендации для будущего: не использовать «магические числа» в петлях, объявить их в качестве переменной, а затем вы можете просто изменить это в одном месте, менее вероятное поведение ошибки.

Собран с VS 2015:

#include <iostream> 
#include <fstream> 
#include <cctype> 
#include <cstring> 
#include <iomanip> 
#include <string> 

using namespace std; 

double calcAvg(double[][6], int); 
double calcLow(double[][6], int); 
double calcHigh(double[][6], int); 

struct studInfo 
{ 
    string fname; 
    string lname; 
    double low; 
    double high; 
    double average; 
} ; 

int main() 
{ 
    ifstream input; 
    ifstream input2; 
    double scores[9][6]; 
    string firstName; 
    string lastName; 
    int count = 0; 

    struct studInfo students[9]; 

    input.open("cis_testGrades.txt"); 

    while (!input.eof()) 
    { 
    for (int a = 0; a < 9; a++) 
    { 
     cout << "Student " << a + 1 << ": "; 
     for (int b = 0; b < 6; b++) 
     { 
     input >> scores[a][b]; 
     cout << scores[a][b] << " "; 
     } 
     cout << " " << endl; 
    } 
    } 
    input.close(); 

    /*cout << calcAvg(scores, 9) << endl; 
    cout << calcHigh(scores, 9) << endl; 
    cout << calcLow(scores, 9) << endl;*/ 

    input2.open("cis_students.txt"); 

    while (!input2.eof()) 
    { 
    input2 >> firstName; 
    students[count].fname = firstName; 
    //strcpy(students[count].fname, firstName); 

    input2 >> lastName; 
    students[count].lname = lastName; 
    //strcpy(students[count].lname, lastName); 

    students[count].low = calcLow(scores, count); 

    students[count].high = calcHigh(scores, count); 

    students[count].average = calcAvg(scores, count); 

    count++; 
    } 

    input2.close(); 

    for (int a = 0; a < 9; a++) 
    cout << students[a].fname << " " << students[a].lname << " " << students[a].low << " " << students[a].high << " " << students[a].average << endl; 

    return 0; 
} 

    double calcAvg(double grades[][6], int student) 
    { 
    double average; 
    double sum = 0; 

    for (int a = 0; a < 6; a++) 
     sum += grades[student][a]; 

    average = sum/6; 

    return average; 
    } 

    double calcHigh(double grades[][6], int student) 
    { 
    double high = 0; 

    for (int a = 0; a < 6; a++) 
    { 
     if (grades[student][a] >= high) 
     high = grades[student][a]; 
    } 
    return high; 
    } 

    double calcLow(double grades[][6], int student) 
    { 
    double low = 100; 

    for (int a = 0; a < 6; a++) 
    { 
     if (grades[student][a] <= low) 
     low = grades[student][a]; 
    } 
    return low; 
    } 
+0

Это будет ошибка: 'while (! Input.eof())'.[Почему iostream :: eof внутри условия цикла считается неправильным?] (Http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301

0

В

double calcAvg(double grades[9][6], int student) 

sum определяется как

double sum; 

но не инициализируется перед

sum += grades[student][a]; 

поэтому значение суммы в начале операции неизвестна. Может быть равен нулю. Может быть миллиард.

Решение: Инициализировать сумму.

double sum = 0; 

Кроме того, в double calcHigh (double grades[][6], int student)

if (grades[student-1][a] >= high) 

student-1 почти наверняка не student чьи классы вы хотите вычислить. В тех случаях, когда это не так плохо, студент 0, который будет вычисляться по grades[-1], который не существует и вызывает неопределенное поведение.

Решение

if (grades[student-1][a] >= high) 

calcLow имеет ту же проблему.

Смежные вопросы