2014-10-24 2 views
0

Вот продолжение моей предыдущей программы. Он не будет печатать правильную информацию для среднего. Пожалуйста помоги.Найти среднее значение в 2D-массиве: FIXED

PRINT

Listed below is your totals within each Motion Picture Company 
---------------------------------------------------------------- 
Name    |Paramount |Century Fox |Warner |WaterFront |Total 

Alyssa |  20|  30|   0|  40|   0|     |90 

Total: 90 
Average: inf 
Max: 40 

Мой КОД: Я пытаюсь добавить средние суммы в моем массиве печати. Кажется, что возвращает искомую информацию в требуемом поле, и я не могу понять, почему. Надеюсь, кто-то может мне скоро помочь!

#include <iostream> 
#include "motionPicture.h" 
#include <iomanip> //to use setw 
#include <cstring> 
#include <string> 

using namespace std; 

int motionPicture :: count = 0; 

motionPicture :: motionPicture() { 

    //initalize the table 
    for (int i =0; i < rows; i++){ 

      for (int j=0; j<columns; j++){ 

        table[i][j] =0; 
      }//end j for loop 
    }//end i for loop 
}//end constructor 

Часть ввода от моей функции GetData():

int rowNum=0; 
    rowNum++; 
    string1[count] = name; 
    count++; 

    cout <<"Input the data in the following format."<<endl; 
    cout <<"Motion Picture Number <space> Cost of movies "<<endl; 
    cout <<"Enter -1 <space> 0 to end"<<endl<<endl; 

    cin >> motion >> cost; 

    while (motion != -1) { 

        table[rowNum-1][motion-1] +=cost; 

        cout <<"Enter Motion Picture <space> Cost of movies" <<endl; 
        cin >> motion >>cost; 
      }//end cost while 

печати массив, который имеет проблемы для средней выходной

void motionPicture :: printArray() { 
//need to pass an int in array element variable 
int size =0; 
size =sizeof(table)/ sizeof(table[0][0]); 
double max = table[0][0]; 
double min = table[0][0]; 

cout <<"Listed below is your totals within each Motion Picture Company"<<endl; 
cout <<"----------------------------------------------------------------"<<endl; 

cout<<"Name" << setw(15)<<'|'<<setw(5)<< "Paramount" <<setw(5)<<'|'<<setw(5)<< "Century Fox" <<setw(5)<<'|'<<setw(5)<< 
    "Warner"<<setw(5)<<'|'<<setw(5) <<"WaterFront" <<setw(5)<<'|'<<setw(5)<<"Total"<<endl<<endl; 

    for (int i= 0; i <count; i++){ 
       double total =0; 
       double average = 0; 
       cout<<string1[i]<<setw(5)<<'|'; 

     for (int j=0; j<columns; j++) { 

       //cout <<string1[i]<<"\t"; 
       cout <<setw(10)<<table[i][j]<<'|'; 
       //input total 

       total += table[i][j]; 
       // double totalSales = total; 
//    average = i[i][j] + j[i][j]'//totalSales/(i*j); 
       average= total/table[i][j]; 
       if (table[i][j] > min) 
         max = table[i][j]; 
       else if (table[0][0] < min) 
         min = table[i][j]; 

     }//end j loop 

    cout <<setw(20)<<'|'<<total<<"\n"; 
    cout<<endl; 
    cout <<"Total: "<<total<<endl; 
    cout<<"Average: " <<average/table[rowNum][motion]<<endl; 
    cout<<"Max: " <<max<<endl<<endl; 

    }//end i loop 
}//end print 

ФУНКЦИЯ КОРРЕКЦИИ

void motionPicture :: printArray() { 
//need to pass an int in array element variable 
int size =0; 
size =sizeof(table)/ sizeof(table[0][0]); 
double max = table[0][0]++; 
double min = table[0][0]++; 


cout <<"Listed below is your totals within each Motion Picture Company"<<endl; 
cout <<"----------------------------------------------------------------"<<endl; 

cout<<"Name" << setw(10)<<'|'<<setw(5)<< "Paramount" <<setw(5)<<'|'<<setw(5)<< "Cent Fox" <<setw(6)<<'|'<<setw(5)<< 
    "Warner"<<setw(8)<<'|'<<setw(5) <<"WaterFront" <<setw(4)<<'|'<<setw(5)<<"Total"<<endl<<endl; 

    for (int i= 0; i <count; i++){ 
       double total =0; 
       double average = 0; 
       cout<<string1[i]<<setw(8)<<'|'; 

     for (int j=0; j<columns; j++) { 

       //cout <<string1[i]<<"\t"; 
       cout <<setw(7)<<table[i][j]<<setw(7)<<'|'<<setw(7); 
       //input total 

       total += table[i][j]; 
       average = total/columns; 
       if (table[i][j] > min) 
         max = table[i][j]; 
       else if (table[0][0] < min) 
         min = table[i][j]; 



     }//end j loop 

    cout <<setw(5)<<total<<"\n"; 
    cout<<endl; 
    cout <<"Total: "<<total<<endl; 
    cout<<"Average: " <<average<<endl; 
    cout<<"Max: " <<max<<endl<<endl; 

    }//end i loop 
}//end print 

ПРАВИЛЬНАЯ ПЕЧАТЬ! :)

Listed below is your totals within each Motion Picture Company 
---------------------------------------------------------------- 
Name   |Paramount |Cent Fox  |Warner  |WaterFront |Total 

Alyssa  |  22  |  20  |  0  |  0  | 42 

Total: 42 
Average: 10.5 
Max: 22 

Wes  |  40  |  60  |  0  |  0  | 100 

Total: 100 
Average: 25 
Max: 60 
+2

Слишком много нерелевантного кода для проскальзывания. –

+0

Должен ли я показывать только мой массив печати? – narue1992

+1

См. Справочный центр по созданию [«Минимальный, полный, проверяемый пример»] (http://stackoverflow.com/help/mcve). Комментируемый код не должен включаться, не нужно форматировать (если это не вопрос о форматировании) или * «Добро пожаловать в нашу систему хранения для вашей учетной записи» *. Если вход не является вашей проблемой, тогда лучше просто скопировать данные в программу. Независимо от того, какая минимальная программа демонстрирует аспект проблемы, о которой вы хотите спросить, это пример кода. * И убедитесь, что ваш образец * компилирует * и демонстрирует проблему! * – HostileFork

ответ

0

average должна быть рассчитана путем деления суммы на количество записей. У вас есть общее количество в total и количество записей в columns (при условии, что вам требуется среднее значение столбца). Поэтому вам просто нужно иметь это в конце цикла столбца (j).

average = total/columns; 

и распечатать это. Или, проще говоря, вы можете просто распечатать total/columns.

+0

Я бы хотел, чтобы средний показатель для всех столбцов. Я пробовал этот код, но когда у меня есть Paramount = 20 и Cent Fox = 30 (всего 50), то он дает мне Average: 10 – narue1992

+0

ну, я думаю, это имело бы смысл, так как есть 5 столбцов. остальное = 0, так что технически это правильно. Думаю, это лучшее, что я могу сделать, если человек не вводит информацию только для всех столбцов. – narue1992

+0

спасибо. Наверное, все было так просто. Я пытался выяснить, какой код слишком сложный. – narue1992