C++ Class Definition Average an array of Measure objects input by user

Description

C++ Class Definition Average an array of Measure objects input by user

#include <iostream>
using namespace std;
class Measure                    // English Measure class
{
   private:/*from ww w.j av  a  2s  .  co  m*/
   int feet;
   float inches;
   public:
   Measure()
   { feet = 0; inches = 0; }
   Measure(int ft, float in)
   { feet = ft; inches = in; }
   void getdist()              //get length from user
   {
      cout << "\nEnter feet: ";  cin >> feet;
      cout << "Enter inches: ";  cin >> inches;
   }
   void showdist()
   { cout << feet << "\'-" << inches << '\"'; }
   void add_dist( Measure, Measure );    //declarations
   void div_dist( Measure, int );
};
//add Measures d2 and d3
void Measure::add_dist(Measure d2, Measure d3)
{
   inches = d2.inches + d3.inches;  //add the inches
   feet = 0;                      //(for possible carry)
   if(inches >= 12.0)             //if total exceeds 12.0,
   {                           //then decrease inches
       inches -= 12.0;             //by 12.0 and
       feet++;                     //increase feet
   }                           //by 1
   feet += d2.feet + d3.feet;     //add the feet
}
//divide Measure by int
void Measure::div_dist(Measure d2, int divisor)
{
    float fltfeet = d2.feet + d2.inches/12.0;  //convert to float
    fltfeet /= divisor;                        //do division
    feet = int(fltfeet);                       //get feet part
    inches = (fltfeet-feet) * 12.0;            //get inches part
}
int main()
{
    Measure distarr[100];         //array of 100 Measures
    Measure total(0, 0.0), average;  //other Measures
    int count = 0;                 //counts Measures input
    char ch;                       //user response character
    do {
       cout << "\nEnter a Measure";           //get Measures
       distarr[count++].getdist();             //from user, put
       cout << "\nDo another (y/n)? ";         //in array
       cin >> ch;
    }while( ch != 'n' );
    for(int j=0; j<count; j++)                 //add all Measures
       total.add_dist( total, distarr[j] );    //to total
    average.div_dist( total, count );          //divide by number
    cout << "\nThe average is: ";              //display average
    average.showdist();
    cout << endl;
    return 0;
}



PreviousNext

Related