Assume that the fraction structurecontains two members: numerator and denominato
ID: 3614670 • Letter: A
Question
Assume that the fraction structurecontains two members: numerator anddenominator (both of type int). Writefunctions that perform the following operations on fractions:
a) Reduce the fraction f to lowestterms. Hint: To reduce a fraction to lowest terms, first computethe greatest common divisior (GCD) of the numerator anddenominator. Then divide both the numerator and denominator by theGCD.
b) Add the fractions f1 andf2.
c)Subtract the fractions f2 from thefraction f1.
d) Multiply the fractions f1 andf2.
e) Divide the fractions f1 by thefraction f2.
The fractions f, f1, andf2 will be arguments of typestruct fraction; each function willreturn a value of type struct fraction.The fractions returned by the functions in parts (b)-(e) should bereduced to lowest terms. Hint: You may use the function from part(a) to help write the functions in parts (b)-(e).
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
struct fraction{
int num,deno;
};
int gcd(int a, int b)
{
if( a==b)
return a;
else
if (a>b)
return gcd(a-b,b);
else
return gcd(a,b-a);
}
struct fraction reduce(struct fraction f)
{
int m;
m = gcd(f.num, f.deno);
f.num = f.num/m;
f.deno = f.deno/m;
return f;
}
struct fraction add(struct fraction f1,struct fraction f2)
{
int n,d,m;struct fraction f3;
n=f1.num*f2.deno + f2.num*f1.deno;
d=f1.deno * f2.deno;
m=gcd(n,d);
n=n/m;
d=d/m;
f3.num = n;
f3.deno = d;
return f3;
}
struct fractionsubtract(struct fraction f1,struct fraction f2)
{
int n,d,m;struct fraction f3;
n=f1.num*f2.deno - f2.num*f1.deno;
d=f1.deno * f2.deno;
if(n!=0)
{
m=gcd(n,d);
n=n/m;
d=d/m;
}
f3.num = n;
f3.deno = d;
return f3;
}
struct fraction multiply(struct fraction f1,struct fraction f2)
{
int n,d,m;struct fraction f3;
f3.num = f1.num *f2.num;
f3.deno = f1.deno * f2.deno;
m=gcd(f3.num,f3.deno);
f3.num /=m;
f3.deno /=m;
return f3;
}
struct fractiondivide(struct fraction f1,struct fraction f2)
{
int n,d,m;struct fraction f3;
f3.num = f1.num *f2.deno;
f3.deno = f1.deno * f2.num;
m=gcd(f3.num,f3.deno);
f3.num /=m;
f3.deno /=m;
return f3;
}
int main()
{
struct fraction f1,f2,f3;
f1.num = 32;
f1.deno = 20;
f2.num = 3;
f2.deno = 20;
f3 = reduce(f1);
printf("Reduced fraction is %d/%d ",f3.num,f3.deno);
f3 = add(f1,f2);
printf("Added fraction is%d/%d ",f3.num,f3.deno);
f3 = subtract(f1,f2);
printf("Subtract fraction is%d/%d ",f3.num,f3.deno);
f3 = multiply(f1,f2);
printf("Multiply fraction is%d/%d ",f3.num,f3.deno);
f3 = divide(f1,f2);
printf("divide fraction is%d/%d ",f3.num,f3.deno);
system("pause");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.