data-structures · intermediate · ~15 min

Compare fractions

Use a typedef'd struct and compare without floating point.

Challenge

Define typedef struct { int num, den; } Frac; (positive denominators) and implement int frac_cmp(Frac a, Frac b) returning -1, 0, or 1 for a<b, a==b, a>b. Compare by cross-multiplication.

Starter code

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.