Without using math. Write a rational number of the form m/n can be stored in an
ID: 3621626 • Letter: W
Question
Without using math. Write a rational number of the form m/n can be stored in an integer array arr of size 2 by assigning a[0]=m and a[1]=n. Write three functions, declared as follows:
int Gcd (int x, int y);
void Reduce (int x[]);
void Add (int rat1[], int rat2[]);
Gcd takes two integers and returns their greatest common divisor. Reduce takes a rational number in the form of an integer array and changes the entries of the array by canceling the gcd of the two entries. For example, the operation Reduce (int x) for x=[4, 6] should change x to [2, 3]. The function Add (int x[], int y[]) adds the rational numbers stored in the two input arrays x and y and and stores the output in reduced form in the first array (x).
main should ask the user for two (positive) rational numbers and store them in two arrays of size 2 each. It then calls Reduce and prints both the inputs in the reduced form. Finally, it calls Add to add the two inputs and prints the result. Sample runs of the program are shown below.
(~)$ a.out
Enter r1: 2/3
Enter r2: 3/9
Reduced r1=2/3
Reduced r2=1/3
Sum=1/1
(~)$ a.out
Enter r1: 12/54
Enter r2: 5/30
Reduced r1=2/9
Reduced r2=1/6
Sum=7/18
Explanation / Answer
Here is the 3 functions. I didn't write the main function since I assume this much knowledge if not just use stdio or stdlib (i forgot which) and use scanf to get input. so something like this ..... printf("Enter Number 1:"); scanf("%d",var1); //and repeat. Hope this helps! int Gcd(int x, int y) { int a = 0; int b = 0; if (x > y) b = x; else b = y; for (a = b; a > 0; a--) { if (x%a == 0 && x%a == 0) return a; } } void Reduce (int x[]) { int gcd = Gcd(x[0],x[1]); x[0]/= gcd; x[1]/= gcd; } void Add(int rat1[], int rat2[]) { rat1[0] *= rat2[1]; rat2[0] *= rat1[1]; int temp = rat1[1] * rat2[1]; rat1[1] = temp; rat2[1] = temp; //i use rat1 to get the added numbers you can create a temp var if you want. rat1[0] = rat1[0] + rat2[0] //call it so it gets reduced Reduce(rat1[0],rat1[1]); //print how you like. note: / may not be the way to print that double check?? printf("Sum=%d/%d",rat1[0],rat1[1]); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.