How to make a CMinMaxAvg class

I got asked how to create a simple averaging class.
If you where feeling smart you could enhance this class in to a template class for a object that has the =,+,>,< operator. But I’m feeling lazy today.

class CMinMaxAvg
{
private :
int	m_count;
int	m_total;
int	m_min;
int	m_max;
public:

CMinMaxAvg() {
m_count = 0 ;
m_total = 0 ;
m_min   = 0 ;
m_max   = 0 ;
}

void add( int iNum ) {
if( m_count == 0 ) {
SetMax( iNum, true ) ;
SetMin( iNum, true );
}        SetMax( iNum, false );
SetMin( iNum, false );
m_count ++;
m_total += iNum ;
}

void SetMax( int iNum, bool force=true ) {
if( m_max < iNum || force ) {
m_max = iNum ;
}
}

void SetMin( int iNum, bool force=true ) {
if( m_min > iNum || force) {
m_min = iNum ;
}
}

float GetAvg( ) {
return (float)m_total/(float)m_count ;
}

int GetMax() {
return m_max ;
}

int GetMin() {
return m_min ;
}
};

One Response to How to make a CMinMaxAvg class

  1. Aleph says:

    Even better would be to make it a template class. Much more useful, especially if the standard operators are overriden correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>