Write a C program that performs arithmetic’s operation with fractions using four different functions (for addition, subtraction, multiplication and division). Use two integer variables to represent the numerator and the denominator as arguments to the functions. The functions should perform the following:
Printing Rational numbers in the form "a/b" where "a" is the numerator and "b" is the denominator.
In your function to print the Rational number, when the denominator is equal to zero, it must show the error message "DIVIDE BY ZERO ERROR!!!" Otherwise, print the Rational number in the required format.
#include <stdio.h>
int gcd(int m, int n) {
if (n == 0) {
return m;
}
return gcd(n, m%n);
}
typedef struct {
int numerator;
int denominator;
} Rational;
void Addition(Rational* a, Rational* b, Rational* res) {
int divisor;
res->numerator = a->numerator*b->denominator
+ b->numerator*a->denominator;
res->denominator = a->denominator*b->denominator;
divisor = gcd(abs(res->numerator), abs(res->denominator));
res->numerator /= divisor;
res->denominator /= divisor;
}
void Subtraction(Rational* a, Rational* b, Rational* res) {
int divisor;
res->numerator = a->numerator*b->denominator
- b->numerator*a->denominator;
res->denominator = a->denominator*b->denominator;
divisor = gcd(abs(res->numerator), abs(res->denominator));
res->numerator /= divisor;
res->denominator /= divisor;
}
void Multiplication(Rational* a, Rational* b, Rational* res) {
int divisor;
res->numerator = a->numerator*b->numerator;
res->denominator = a->denominator*b->denominator;
divisor = gcd(abs(res->numerator), abs(res->denominator));
res->numerator /= divisor;
res->denominator /= divisor;
}
void Division(Rational* a, Rational* b, Rational* res) {
int divisor;
res->numerator = a->numerator*b->denominator;
res->denominator = a->denominator*b->numerator;
divisor = gcd(res->numerator, res->denominator);
res->numerator /= divisor;
res->denominator /= divisor;
}
void Print(Rational* r) {
if (r->denominator == 0) {
printf("DIVIDE BY ZERO ERROR!!!");
}
else {
printf("%d/%d", r->numerator, r->denominator);
}
}
int main() {
Rational r1, r2, r3;
r1.numerator = 1;
r1.denominator = 2;
r2.numerator = 2;
r2.denominator = 3;
Addition(&r1, &r2, &r3);
Print(&r1); printf(" + "); Print(&r2); printf(" = "); Print(&r3); printf("\n");
Subtraction(&r1, &r2, &r3);
Print(&r1); printf(" - "); Print(&r2); printf(" = "); Print(&r3); printf("\n");
Multiplication(&r1, &r2, &r3);
Print(&r1); printf(" * "); Print(&r2); printf(" = "); Print(&r3); printf("\n");
Division(&r1, &r2, &r3);
Print(&r1); printf(" : "); Print(&r2); printf(" = "); Print(&r3); printf("\n");
return 0;
}
Comments
Leave a comment