0

i need to create a class named rational, and i need to have the integer variables denominator and numerator in private. The i need to provide a constructor that enables an object of the class to be initialized when it is declared. then it says the constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. so 2/4 should be stored in the object as 1 in the numerator, and 2 in the denominator. heres what i have done so far, im really confused.

#include <iostream>

class rational {

public:






private:

int numerator;
int denominator;


}; // end of rational class

int main()
{











return 0;
}
3
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by Dave Sinkula
0

For starters, you'll need 2 constructors. One will be something like

rational(int m, int n)
{  num = m;
    den = n; //You really should check for n == 0
}

and the other (the default) would be

rational()
{  num = 0;
    den = 1;
}

In order to do the reduced form (i.e., 1/2 instad of 2/4) you'll need t owrite a program for the Euclidian (gcd) algorithm, or get it from somewhere.

Edited by Dani: Fixed formatting

0

For starters, you'll need 2 constructors. One will be something like

rational(int m, int n)
{  num = m;
    den = n; //You really should check for n == 0
}

and the other (the default) would be

rational()
{  num = 0;
    den = 1;
}

This could also be done like this.

class rational
{
   int numerator, denominator;
public:
   rational(int n = 0, int d = 1) : numerator(n), denominator(d)
   {
      // additional code
   }
};
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.