A rational number is a quotient of two integers with a nonzero denominator. A C representation stores a sign, numerator, and denominator; distinct representations such as 6/15 and 2/5 can denote the same value. section 10.2.2
Pure operations maintain a useful representation:
- Normalize by dividing numerator and denominator by their greatest common divisor. section 10.2.2
- Extend by multiplying both parts by the same factor when a common denominator is needed. section 10.2.2
- Compute products by multiplying numerators and denominators, and compute sums after aligning denominators; normalize returned results. section 10.2.2
Listing 10.1 A type for computation with rational numbers
#ifndef RATIONALS_H
# define RATIONALS_H 1
# include <stdbool.h>
# include "euclid.h"
typedef struct rat rat;
struct rat {
bool sign;
size_t num;
size_t denom;
};
/* Functions that return a value of type rat. */
rat rat_get(signed sign, size_t num, size_t denom) [[__unsequenced__]];
rat rat_get_normal(rat x) [[__unsequenced__]];
rat rat_get_extended(rat x, size_t f) [[__unsequenced__]];
rat rat_get_prod(rat x, rat y) [[__unsequenced__]];
rat rat_get_sum(rat x, rat y) [[__unsequenced__]];
/* Functions that operate on pointers to rat. */
void rat_destroy(rat* rp) [[__unsequenced__]];
rat* rat_init(rat* rp,
signed sign,
size_t num, size_t denom) [[__unsequenced__]];
rat* rat_normalize(rat* rp) [[__unsequenced__]];
rat* rat_extend(rat* rp, size_t f) [[__unsequenced__]];
rat* rat_sumup(rat* rp, rat y) [[__unsequenced__]];
rat* rat_rma(rat* rp, rat x, rat y) [[__unsequenced__]];
/* Functions that are implemented as exercises. */
/** @brief Print @a x into @a tmp and return tmp. **/
char const* rat_print(size_t len, char tmp[len], rat const* x);
/** @brief Print @a x normalize and print. **/
char const* rat_normalize_print(size_t len, char tmp[len],
rat const* x);
rat* rat_dotproduct(rat rp[static 1], size_t n,
rat const A[n], rat const B[n]);
#endif
Inspect the C type and value-returning operations for rational arithmetic. section 10.2.2


