GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 08-Jun-2005, 09:26
breggo breggo is offline
New Member
 
Join Date: Jun 2005
Posts: 2
breggo is on a distinguished road

Problem with program


Hi! I have this problem with my program... I'm making a program which you add students into and their grades, and the program calculates average score for boys and girls and all students. However, when I try running it, I can add students without trouble, but when I check on the statistics, it just says that I havent added any students...
Could someone please help me?
example run
Code:
Menu selection: 1.Add student data 2.Randomize student data 3.show statistics 4.Exit 1 Specify sex of student; 1 (girl) or 0 (boy): 0 Specify student grade: (1-5) 5 Menu selection: 1.Add student data 2.Randomize student data 3.show statistics 4.Exit 1 Specify sex of student; 1 (girl) or 0 (boy): 0 Specify student grade: (1-5) 1 Menu selection: 1.Add student data 2.Randomize student data 3.show statistics 4.Exit 3 Boys average score: ---------------------- Number of boys:0 Average score:0 Girls average score: ---------------------- Number of girls:0 Average score:0 Total average score: ---------------------- Number of students:0 Average score:0

My current code is:
main.cpp
CPP / C++ / C Code:
#include <iostream>
#include "student.h"
#include "calc.h"
using std::cin; 
using std::cout;
using std::endl;

int main(int argc, char *argv[])
{   
    int SEL, loop=1, x;
    klass klass1;        // Initiera ett objekt, "Klass", av klassen Klass    
    while(loop==1)
    {
        cout << "Menu selection:\n1.Add student data\n2.Randomize student data\n3.show statistics\n4.Exit" << endl;
        cin >> SEL;
        switch(SEL)
        {
            case 1: 
                klass1.addstudent();
            break;
            case 2:
                cout << "not implemented yet!";
            break;
            case 3:
                klass1.collect();
                klass1.calcaverage();
                cout << "Boys average score:\n----------------------\nNumber of boys:" << klass1.numBo() << "\nAverage score:" << klass1.AvGradeBoys() << endl << endl;
                cout << "Girls average score:\n----------------------\nNumber of girls:" << klass1.numGi() << "\nAverage score:" << klass1.AvGradeGirls() << endl << endl;
                cout << "Total average score:\n----------------------\nNumber of students:" << (klass1.numGi()+klass1.numBo()) << "\nAverage score:" << klass1.averagegrade() << endl;
                cin.ignore(255,'\n');
                cin.get();
            case 4:
                return 0;
            default:
                cout << "ERROR" << endl;
        }
    }
	/*klass1.collect();
	klass1.calcaverage();
	cout << "Boys average score:\n----------------------\nNumber of boys:" << klass1.numBo() << "\nAverage score:" << klass1.AvGradeBoys() << endl << endl;
	cout << "Girls average score:\n----------------------\nNumber of girls:" << klass1.numGi() << "\nAverage score:" << klass1.AvGradeGirls() << endl << endl;
	cout << "Total average score:\n----------------------\nNumber of students:" << (klass1.numGi()+klass1.numBo()) << "\nAverage score:" << klass1.averagegrade() << endl;
	*/
    cin.ignore(255,'\n');
    cin.get();
    return 0;
}

calc.cpp
CPP / C++ / C Code:
#include "calc.h"
#include "student.h"
using namespace std;


klass::klass() : numG(0), numB(0), AvGradeG(0), AvGradeB(0), totGrade(0), numofstud(0), Ggrade(0), Bgrade(0)
{
}

klass::~klass()
{
}

void klass::collect()
{	

	for(int i=(numG+numB);i>0;i--)
	{
		if(getGender())             // om getGender() är sann = tösabete...
		{
			Ggrade=Ggrade+getGrade();
			numG++;
		} 

		else                        // ...annars en hane
		{
			Bgrade=Bgrade+getGrade();
			numB++;  
		}
	}
}


void klass::calcaverage()
{
	if(numG>0)                      // Inte dela med noll
		AvGradeG=Ggrade/numG;

	if(numB>0)                      // inte dela med noll
		AvGradeB=Bgrade/numB;

	if((numB+numG)>0)               // inte dela med noll
		totGrade=(Bgrade+Ggrade)/(numB+numG);
}

float klass::AvGradeGirls()         // medelbetyg för tjejer
{
	return AvGradeG;
}

float klass::averagegrade()         // medelbetyg
{
	return totGrade;
}

int klass::totalStudents()
{
    return numG+numB;
}


float klass::AvGradeBoys()          // medelbetyg för killar
{
	return AvGradeB;
}

int klass::numBo()                  //  Antal B
{
	return numB;
}

int klass::numGi()                  // Antal G
{
	return numG;
}

void klass::addstudent()
{
	stud[numofstud].setGender();
	stud[numofstud].giveGrade();
    numofstud++;
}

student.cpp
CPP / C++ / C Code:
#include "student.h"
using namespace std;
// Funktioner

void student::setGender()        // FALSE=boy, TRUE=girl
{   
    bool done = false;
    while (!done)
    {
        int num;
        std::cout << "Specify sex of student; 1 (girl) or 0 (boy): ";
        std::cin >> num;
        switch( num )
        {
             case 0:
                 gender = false;
                 done = true;
                 break;
             case 1:
                  gender = true;
                  done = true;
                  break;
              default:
                  std::cout << "You must enter 0 or 1: " << endl;
        }
    }
}

void student::giveGrade()
{
     std::cout << "Specify student grade: (1-5) ";
     std::cin >> grade;
}

float student::getGrade()
{
	return grade;
}

bool student::getGender()
{
	return gender;
}

calc.h
CPP / C++ / C Code:
#ifndef CALC_H
#define CALC_H
  
#include"student.h"
#define students 20




class klass : public student 
{
public:

     klass();
     virtual ~klass();
     float AvGradeGirls();      //{return AvGradeG;} medelbetyg för tjejer
     float averagegrade();      //{return totGrade;} medelbetyg
     float AvGradeBoys();       //{return AvGradeB;}  medelbetyg för killar
     void addstudent(); 
     int numBo();               // Antal B
     int numGi();               // Antal G
     int totalStudents();       // Totala antalet studneter
     void collect();
     void calcaverage();


private:

     student stud[students];
     int Ggrade;
     int Bgrade;                // Tjejsor och killsars sammanlagda betyg (ej  medelvärde)
     int numofstud;
     int numG;
     int numB;
     double AvGradeB;           // Gossars betyg
     double AvGradeG;           // Flickors betyg
     double totGrade;           // Totala betyget
};

#endif // CALC_H

student.h
CPP / C++ / C Code:
/* Skapar elever, tilldelar dem kön samt betyg */
    
    
#ifndef STUDENT_H
#define STUDENT_H
    
#include <iostream>
    
using std::cin;
using std::cout;
    
class student
{
public:
    
    //student();
    //~student();
    void setGender();      // FALSE=boy, TRUE=girl
    void giveGrade();
    float getGrade();      //{return grade;}
    bool getGender();      //{return gender;}
    
private:
 
    bool gender;
    double grade;
};
    
#endif // STUDENT_H
Last edited by LuciWiz : 08-Jun-2005 at 09:40. Reason: Please insert your C++ code between [c++] & [/c++] tags
  #2  
Old 08-Jun-2005, 10:18
maprich maprich is offline
Member
 
Join Date: May 2005
Posts: 163
maprich has a spectacular aura aboutmaprich has a spectacular aura about
Ok in klass::addstudent() you call student::setGender() and student::giveGrade(). So these infos are going to be stored in the student objects, not in the klass object. In printing the info you call klass::numBo() but the problem is that
Quote:
Originally Posted by breggo
Code:
int klass::numBo() // Antal B { return numB; }
returns numB from the klass and your code never puts anything there. The data is in stud[numofstud] which is an object of class klass.

you should modify klass::addstudent like this:
Code:
void klass::addstudent() { int gend = stud[numofstud].setGender(); int grad = stud[numofstud].giveGrade(); numofstud++; if( gend == 0 ) { numB++; Bgrade += grad; } else { numG++; Ggrade += grad; } }
where you have to modify the student::setGender() and student::giveGrade() as well.

And if I may comment the general logic of your software. Your class klass seems to be the holder of statistical data and student is information about one student. The structuring seems very complicated to me. main function holds the klass object which holds multiple student objects in an array. In my opinion simple is better so you could have the array of student objects in the main function (if you really need the student class in the first place) also directly in the main function you could hold an object of class Statistics which includes all your statistics data. Then you ask the data in a loop as you do now and update directly the statistics object as well as manipulate the student objects in your array.

Also it is cryptic to code everything with numbers. Using enumerations would make the code more nice to read.
  #3  
Old 08-Jun-2005, 10:45
breggo breggo is offline
New Member
 
Join Date: Jun 2005
Posts: 2
breggo is on a distinguished road
Thanks alot for the help!
Okey, perhaps my logic sucks, but this is my first attempt at using nested classes, and thats why I thought I had to put the student in klass. I didn't really understand what you said to me, I tried changing the addStudent() and the printout to stud[numofstud], but it keeps complaining about neither stud nor numofstud being declared.

Don't take this as me just being lazy, but I'm fed up with this program now, It just keep getting me errors... Would anyone perhaps try and take on the program to make it work? Post a working version? I really don't want to abandon this project, I really want to learn this, but as things are now, I'm very discuraged.
Could someone please help me?
  #4  
Old 08-Jun-2005, 14:51
maprich maprich is offline
Member
 
Join Date: May 2005
Posts: 163
maprich has a spectacular aura aboutmaprich has a spectacular aura about
Ok.. because I had nothing much to do, and it seems that you have tried really hard, I decided to make an exception of the rule and write quickly some skeleton program that simulates the functionality in your program. Adding functionality will remain your task. And I dropped away that student class. You can add it if you feel that you need it.
Anyway here it is in 3 files:

statistics.h
CPP / C++ / C Code:
#ifndef STATISTICS_H
#define STATISTICS_H

#include <vector>
#include <string>
using namespace std;

class Statistics
{
      public:
             Statistics( vector<string> *catNames );
             ~Statistics();
             bool AddData( string category, int value );
             double GetMean( string category );
             double GetReallyMean();
             int getAmountInCategory( string category ); 
      private:
             vector<string> categoryNames;
             vector< vector<int> > values; 
};       

#endif

statistics.cpp
CPP / C++ / C Code:
#include "statistics.h"

Statistics::Statistics( vector<string> *catNames ) {
    int len = catNames->size();
    categoryNames = *catNames;
    for(int i=0; i<len; i++ ) values.push_back( vector<int>(0) );
}

Statistics::~Statistics() {
    categoryNames.clear();
    for(int i=0; i<categoryNames.size(); i++ ) values[i].clear();
    values.clear();
}

bool Statistics::AddData( string category, int value ) {
     for( int i=0; i<categoryNames.size(); i++ ) {
          if( categoryNames[i] == category )
              values[i].push_back( value );
     }
     return true;
}
double Statistics::GetMean( string category ) {
     int sum = 0, n = 0;
     for( int i=0; i<categoryNames.size(); i++ ) {
          if( categoryNames[i] == category ) {
              n = values[i].size();
              for(int j=0; j<n; j++ ) {
                  sum += values[i][j];
              }
          }
     }
     if( n == 0 ) n = 1;
     return ((double)sum/(double)n);
}

double Statistics::GetReallyMean() {
     double mean = 0.0;
     int n=0, m=0, i;
     for(i=0; i<categoryNames.size(); i++ )
              m += getAmountInCategory( categoryNames[i] );
     if( m == 0 ) m = 1;
     for( int i=0; i<categoryNames.size(); i++ ) {
          n = getAmountInCategory( categoryNames[i] );
          mean += (( (double)n*GetMean( categoryNames[i] ) )/(double)m);
     }
     return mean;
}

int Statistics::getAmountInCategory( string category ) {
    for( int i=0; i<categoryNames.size(); i++ ) {
         if( categoryNames[i] == category ) return values[i].size();
    }
    return 0;
}

main.cpp
CPP / C++ / C Code:
#include <cstdlib>
#include <iostream>

#include "statistics.h"
using namespace std;


int main(int argc, char *argv[])
{
    vector<string> categ; // defines the categories for statistics
    categ.push_back("man"); categ.push_back("woman");
    Statistics *stat = new Statistics( &categ );
    
    // following only if student class really needs to be implemented.
    // vector<Student> stud;
    
    cout<< "Welcome!\n";
    bool notEnded = true;
    int selection;
    while( notEnded ) {
           cout << "\nPlease select operation.\n";
           cout << "\t1. Add student data\n";
           cout << "\t2. Randomize student data\n";
           cout << "\t3. Show statistics\n";
           cout << "\t4. Exit\n";
           cin >> selection;
           
           switch( selection ) {
                 case 1:
                      char sex; int grade;
                      cout << "Entering data. Give 'e' to exit query.\n";
                      while( true ) {
                             cout << "Give the gender of the student(m,w):";
                             cin >> sex;
                             if( sex=='e' || sex=='E' ) break;
                             cout << "Give the grade of the student(1-5):";
                             cin >> grade;
                             if( sex == 'm' ) {
                                 stat->AddData("man", grade );
                             }
                             else {
                                 stat->AddData("woman", grade );
                             }
                             // here put the data to  stud.push_back etc etc if needed.
                      }
                      break;
                 case 2:
                      cout << "\nNothing yet\n\n";
                      break;
                 case 3:
                      cout << endl;
                      cout << "Statistics:\n\n";
                      cout << "Category : men\n";
                      cout << "\tAmount : " << stat->getAmountInCategory("man") << endl;
                      cout << "\tAver. score : " << stat->GetMean("man") << "\n\n";
                      cout << "Category : women\n";
                      cout << "\tAmount : " << stat->getAmountInCategory("woman") << endl;
                      cout << "\tAver. score : " << stat->GetMean("woman") << "\n\n";
                      cout << "Total :\n";
                      cout << "\tAmount : " << (stat->getAmountInCategory("woman")+stat->getAmountInCategory("man")) << endl;
                      cout << "\tAver. score : " << stat->GetReallyMean() << "\n\n";
                      break;
                 case 4:
                 default:
                      notEnded = false;
           }
    }
    categ.clear();
    delete stat;
    system("PAUSE");
    return EXIT_SUCCESS;
}
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 08:44
[TUTORIAL] Calling an external program in C (Linux) dsmith C Programming Language 4 22-Apr-2005 14:30
fltk-2.0 cvs Plumb FLTK Forum 20 13-Nov-2004 08:10
Having a small problem with this program Krc784 C++ Forum 1 04-Nov-2004 23:25
problem with the program under Borland awmp-jansen C Programming Language 3 01-Jul-2004 18:05

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 20:07.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.