CSE2050 Exam #3 11/26/02, Open books, open notes. Name ___________________ 1. The statements below are about a program that calculates expressions of rational numbers. Indicate whether the statement belongs in the analysis or design (5 points each). A. This program accepts integer arithmetic expressions and outputs the exact result as a fraction, e.g. "2/6+1" outputs "4/3". Analysis B. The program uses a class Rational, which represents the quotient of two integers exactly, e.g. -1/5 or 7/3. Design C. The program allows division by 0, e.g. if the input is "3+2/0" then the output is "1/0". Analysis D. Objects of type Rational remove common factors from the numerator and demoninator, e.g. Rational(3,6)==Rational(1,2); Design 2. Suppose i is an int, d is double, and r is Rational. What should the return type be for each of the following expressions? (5 points each). i+r Rational r+d double or r+r Rational d/i double Rational For r+d, i will accept double on the grounds that a double represents a real number and not all reals are rational (e.g. pi, sqrt(2)). I will also accept Rational on the grounds that a double has finite precision in C++ and can't represent any irrational number exactly. Thus, all doubles are rational because they are multiples of some very small power of 2. 3. Write the declarations (no code, no data members) in class Rational for the implicit conversions required by your answer to question 2 (15 points). // ANSWER if r+d is double (promotion is int -> Rational -> double) class Rational { public: Rational(int); operator double() const; }; // If you answered r+d is Rational (int -> double -> Rational) class Rational { public: Rational(double); }; 4. Suppose that division of Rational is defined, e.g. r=r/r; Write operator /= as a non-member function (15 points). // ANSWER Rational& operator /= (Rational& a, const Rational& b) { return a = a / b; } 5. Using only division and conversion, write the multiply operator for Rational (e.g. r*r) as a non-member function (10 points). // ANSWER Rational operator * (const Rational& a, const Rational& b) { return a / (1 / b); // or return a / (Rational(1) / b); } 6. Suppose that class Integer represents integers with an unlimited number of digits, and that Rational allows an unlimited number of digits in both the numerator and denominator. One class is derived from the other. Both types allow conversion from int. Write the derived class with a constructor taking int, including initialization list and any code. (20 points). // ANSWER. All integers are rational, e.g. i = i/1 class Integer: public Rational { public: Integer(int i): Rational(i) {} };