Sample Solution for Take-Home Quiz 4 for CSCI 201
(each question is worth 2 pts)
Below is a class definition (taken from Ch 9):
class RandomInt {
public:
RandomInt(int low = 0, int high = RAND_MAX); ç A
RandomInt(int low, int high, unsigned int seed);
int Draw();
void SetInterval(int low, int high);
void SetSeed(unsigned int seed);
int GetLow() const;
int GetHigh() const;
private:
int low;
int high;
int seed; <=== added in the solution
};
Ans: low, high, and seed
Ans: A constructor. A constructor is used to initialize the data members of a newly created object.
Ans: They are all legal
RandomInt randInt1(1,5), randInt2(100,500);
Ans: The question had errors in formatting that have been corrected above---everybody recieved full credit for this question. The answer should have been (a) and (b). (c) is not legal because the data member low is private and, you can not directly access a private variable outside of a member function. (d) is not illegal because it is an incorrect call to the member function SetSeed(); the correct call looks like: randInt1.SetSeed(5000);
Ans: As discussed in class, you could have taken one of two
approaches to writing this function:
void RandomInt::SetInterval(int low, int high)
{
RandomInt::low = low;
RandomInt::high = high;
}
Alternatively, you could have renamed the parameter so that they did not have the same names as the data members; any names would work:
void RandomInt::SetInterval(int l, int h)
{
low = l;
high = h;
}
Below is the definition of the Rational class that we saw in lecture.
class Rational {
public:
// default constructor
Rational();
// specific constructor
Rational(int numer, int denom = 1);
// arithmetic facilitators
Rational Add(const Rational &r) const;
Rational Multiply(const Rational &r) const;
// stream facilitators
void Insert(ostream &sout) const;
void Extract(istream &sin);
// inspectors
int GetNumerator() const;
int GetDenominator() const;
// mutators
void SetNumerator(int numer);
void SetDenominator(int denom);
private:
// data members
int NumeratorValue;
int DenominatorValue;
};
Rational myRat;
Ans: myRat.SetNumerator(12);
Rational myRat(1,2);
Ans: myRat.Insert(cout);
Rational rat1(1,2), rat2(8,3);
Ans: Rational rat3 = rat2.Multiply(rat1);
#include<iostream.h>
#include "rational.h"
void main() {
Rational rat1(1,2), rat2(8,3);
rat1.Add(rat2);
cout << rat1.GetNumerator() << endl << rat2.GetNumerator() << endl;
}
Ans:
1
8
Ans:
int MaxNum(const Rational &rat1, const Rational &rat2)
{
int num1 = rat1.GetNumerator();
int num2 = rat2.GetNumerator();
if (num1 > num2)
return num1;
else
return num2;
}