Print the Simplified Fraction
In this step, you will enhance the fraction simplification program to handle various input scenarios and provide clear output formatting.
Let's update the program to include more robust fraction printing:
cd ~/project
nano fraction_simplify.c
Update the code with the following implementation:
#include <stdio.h>
// Function to compute GCD using Euclidean algorithm
int computeGCD(int a, int b) {
a = (a > 0) ? a : -a;
b = (b > 0) ? b : -b;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to print fraction with special case handling
void printFraction(int numerator, int denominator) {
// Handle division by zero
if (denominator == 0) {
printf("Error: Division by zero is not allowed.\n");
return;
}
// Compute GCD
int gcd = computeGCD(numerator, denominator);
// Simplify fraction
int simplified_numerator = numerator / gcd;
int simplified_denominator = denominator / gcd;
// Handle sign
if (simplified_denominator < 0) {
simplified_numerator = -simplified_numerator;
simplified_denominator = -simplified_denominator;
}
// Print results
printf("Original Fraction: %d/%d\n", numerator, denominator);
// Different output for whole numbers and fractions
if (simplified_denominator == 1) {
printf("Simplified Fraction: %d\n", simplified_numerator);
} else {
printf("Simplified Fraction: %d/%d\n",
simplified_numerator, simplified_denominator);
}
}
int main() {
int numerator, denominator;
printf("Enter the numerator: ");
scanf("%d", &numerator);
printf("Enter the denominator: ");
scanf("%d", &denominator);
// Call fraction printing function
printFraction(numerator, denominator);
return 0;
}
Compile and run the program:
gcc fraction_simplify.c -o fraction_simplify
./fraction_simplify
Example outputs:
Enter the numerator: 12
Enter the denominator: 18
Original Fraction: 12/18
Simplified Fraction: 2/3
Enter the numerator: 15
Enter the denominator: 5
Original Fraction: 15/5
Simplified Fraction: 3
Enter the numerator: -12
Enter the denominator: 18
Original Fraction: -12/18
Simplified Fraction: -2/3
Code Explanation:
- Added
printFraction()
function to handle fraction printing
- Handles special cases like division by zero
- Manages sign of simplified fraction
- Prints whole numbers when denominator is 1
- Preserves the original sign of the fraction