data-structures · intermediate · ~15 min
Use a typedef'd struct and compare without floating point.
Compare two fractions without converting them to floating point.
Define typedef struct { int num, den; } Frac; and implement int frac_cmp(Frac a, Frac b) that returns -1 if a < b, 0 if a == b, and 1 if a > b. Compare by cross-multiplication, not division.
Two Frac values passed by value. Each has int fields num (numerator) and den (denominator); denominators are positive.
int: -1, 0, or 1.
a={1,2}, b={2,4} -> 0 (equal)
a={1,3}, b={1,2} -> -1 (a < b)
a={3,4}, b={1,2} -> 1 (a > b)
long) for the cross-products to avoid int overflow.a.num*b.den against b.num*a.den.Two Frac values (each int num, den, with positive den), by value.
int: -1, 0, or 1 for a<b, a==b, a>b.
No floating point. Cross-multiply using long to avoid overflow.
typedef struct { int num, den; } Frac;
int frac_cmp(Frac a, Frac b) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.