structure function

I'm writing a function that compares two fraction. if the fractions are equal it returns 0. If the fraction in the first parameter is less than the fraction in the second parameter it returns a negative number. Otherwise it returns a positive number. in doing so convert the fraction to a floating point number.

Im stuck need help completing the function to run


typedef struct fracion
{
int numo;
int denom;
}fraction;

int compareFractions (fracion, fraction);

void main()
{
int x;
fraction f1, f2;
printf("Enter Numo and Demo");
scanf_s("%d%d", &f1.numo, &f1.denom);
printf("Enter Numo and Demo");
scanf_s("%d%d", &f2.numo, &f2.denom);

x = compareFractions(f1, f2);
}

int compareFractions(fraction frac1, fraction frac2)
{
float conf1;
float conf2;

conf1 = frac1.numo / frac1.denom;
conf1 = frac2.numo / frac2.denom;



}
This is integer division: conf1 = frac1.numo / frac1.denom;

This avoids integer division, but floating point comparisons are messy:
1
2
3
4
5
6
7
8
9
/* invariant: a.denom != 0 && b.denom != 0 */
int compareFractions( fraction a, fraction b )
{
    const double f1 = (double)(a.numo) / a.denom ; /* avoid integer division */
    const double f2 = (double)(b.numo) / b.denom ;

    /* compare f1, f2, return result */

} 


Consider using integer comparisons instead:
1
2
3
4
5
6
7
8
9
10
11
/* invariant: a.denom != 0 && b.denom != 0 */
int compareFractions( fraction a, fraction b )
{
    /* comment: const long long common_denom  = (long long)(a.denom) * b.denom ; 
       assumes that the result of multiplying two int values won't overflow long long (usually true) */
    const long long numo_a = (long long)(a.numo) * b.denom ;
    const long long numo_b = (long long)(b.numo) * a.denom ;

    if( numo_a == numo_b ) return 0 ; /* equal */
    else return numo_a < numo_b ? -1 : +1 ;
}
thx alot JLBorges. now i am cleared .
Topic archived. No new replies allowed.