Search code examples
cfunctiondata-structuresstructfractions

How to call a function that simplifies a fraction in C?


This is what I need to do:

Define a structure called “fraction” with integer members “numerator” and “denominator.” Prompt the user to enter a fraction in the form “#/#”. Call a function called “simplFrac” that simplifies a fraction by dividing the numerator and denominator by the greatest common factor and returns the simplified fraction to the calling function. Print the results from main().

And here is my code:

  #include <stdio.h>

  struct fraction {
    int numerator;
    int denominator;
  };

  struct fraction simplFrac(struct fraction x);

 int main(void) {

  struct fraction a;

  printf("Enter a fraction in the form #/#: ");
  scanf("%i/%i",&a.numerator,&a.denominator);

  printf("\n");

  printf("The simplified fraction is: %i/%i\n",);

  return 0;
 }

struct fraction simplFrac(struct fraction x) {
  
  int gcf,remainder;

  while (x.numerator != 0)
   {
      remainder = x.denominator % x.numerator;
      x.denominator = x.numerator;
      x.numerator = remainder;
   }

   gcf = x.denominator;

   x.numerator = x.numerator / gcf;
   x.denominator = x.denominator / gcf;

   return x;
}

Solution

  • Would you please try the following:

    #include <stdio.h>
    
    struct fraction
    {
        int numerator;
        int denominator;
    };
    
    struct fraction simplFrac(struct fraction x);
    int gcf(int, int);
    
    int main(void)
    {
        struct fraction a;
        char buf[BUFSIZ];
    
        printf("Enter a fraction in the form #/#: ");
        fgets(buf, BUFSIZ, stdin);
        sscanf(buf, "%i/%i", &a.numerator, &a.denominator);
    
        a = simplFrac(a);
    
        printf("The simplified fraction is: %i/%i\n", a.numerator, a.denominator);
    
        return 0;
    }
    
    struct fraction simplFrac(struct fraction x)
    {
        int factor = gcf(x.denominator, x.numerator);
    
        x.numerator /=  factor;
        x.denominator /= factor;
    
        return x;
    }
    
    int gcf(int a, int b)
    {
        if (b == 0) return a;
        else return gcf(b, a % b);
    }
    

    The algorythm to calculate the gcf is separated as a function gcf().