Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the program so that the user enters both fractions at the same time, sepa

ID: 3638498 • Letter: M

Question

Modify the program so that the user enters both fractions at the same time, separated by a plus sign:

Enter two fractions separated by a plus sign: 1/2+1/4

The sum is 3/4



#include
#include

int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;

printf("Enter first fraction: ");
scanf("%d/%d", &num1, &denom1);

printf("Enter second fraction: ");
scanf("%d/%d", &num2, &denom2);

result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
printf("The sum is %d/%d ", result_num, result_denom);

return 0;
}

Explanation / Answer

I think something like the following would suffice:
#include <stdio.h>

int gcd(int a, int b) /* euclidian gcd */
{
if(b == 0) return a;
return gcd(b, a % b);
}

int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom, d; /* added d for divisor */

printf("Enter two fractions separated by a plus sign: ");
scanf("%d/%d+%d/%d", &num1, &denom1, &num2, &denom2);

result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
d = gcd(result_num, result_denom);
printf("The sum is %d/%d ", result_num/d, result_denom/d); /* divide by divisor */

return 0;
}

 

 

So whats happening? Well first, the user can now input the desired input of a/b+c/d

Secondly, given those values, it would have calculated (ad+b*c)/(b*d) ... that isn't exactly what we want from the instructions. For if it was 1/2+1/4, the output would have been 6/8.

So we introduce the procedure "GCD" which basically follows Euclid's rule for finding the greater common divisor of two numbers a and b. Basically put, if the output was caculated to be 6/8, gcd of 6 and 8 would find that both are divisible by 2, and so dividing 6 and 8 by 2 would give 3 and 4, as the instruction desired.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote