COP 3223H Lecture -*- Outline -*- * Friday problems with C modules ** rational numbers This problem is about an abstract data type ------------------------------------------ FOR YOU TO DO Implement Rational Numbers, as specified by the following header file. // rational.h #ifndef RATIONAL_H #define RATIONAL_H 1 #include typedef int *ratl; /* requires: denom != 0; * ensures: result is a fresh rational number whose * numerator is num and denominator is denom */ extern ratl rmake(int num, int denom); // ensures: result is the numerator of r extern int numerator(ratl r); // ensures: result is the denominator of r extern int denominator(ratl r); // ensures: result is the sum of x and y extern ratl radd(ratl x, ratl y); // ensures: result is the arithmetic inverse of r extern ratl rnegate(ratl r); // ensures: result is the product of x and y extern ratl rmult(ratl x, ratl y); // requires: the numerator of r is not 0 // ensures: result is the multiplicative inverse of r extern ratl rinverse(ratl r); // ensures: result is true just when r1 and r2 are mathematically equal extern bool requals(ratl r1, ratl r2); #endif ------------------------------------------ ------------------------------------------ DESIGN DECISIONS - How to represent rationals? - How does the representation relate to the mathematical rationals? - Any other possibilities? ------------------------------------------ ... rep as arrays with 2 elements 0 is numerator 1 is denominator ... rep[0] is the numerator, rep[1] is the demominator ... yes, lots. For example: - same idea but with an invariant to keep the fraction in lowest terms (so denominator doesn't divide the numerator) represent num/denom as 2^{num} * 3^{denom} ------------------------------------------ IMPLEMENTING RMAKE #include "rational.h" #define ELEMS 2 ratl rmake(int num, int denom) { ------------------------------------------ Q: How can we return our representation for a rational? Can't return a locally declared array, get dangling pointers Have to allocate the array on the heap ... // needed for malloc #include #define ELEMS 2 ratl rat = (ratl)malloc(sizeof(int[ELEMS])); rat[0] = num; rat[1] = denom; return rat; } ------------------------------------------ FOR YOU TO DO Implement the following functions: // ensures: result is the numerator of r extern int numerator(ratl r); // ensures: result is the denominator of r extern int denominator(ratl r); // ensures: result is the sum of x and y extern ratl radd(ratl x, ratl y); // ensures: result is the arithmetic inverse of r extern ratl rnegate(ratl r); // ensures: result is the product of x and y extern ratl rmult(ratl x, ratl y); // requires: the numerator of r is not 0 // ensures: result is the multiplicative inverse of r extern ratl rinverse(ratl r); // ensures: result is true just when r1 and r2 are mathematically equal extern bool requals(ratl r1, ratl r2); ------------------------------------------ ** complex numbers Could do something similar with complex numbers