Print the Result or Handle Division by Zero
In this step, you will enhance the rational expression program to provide more robust error handling and result presentation.
Update the rational_expressions.c
file to improve output and error handling:
cd ~/project
nano rational_expressions.c
Modify the code to include advanced error handling and result formatting:
#include <stdio.h>
#include <stdlib.h>
int main() {
int numerator, denominator;
// Input validation and error handling
printf("Enter the numerator: ");
if (scanf("%d", &numerator) != 1) {
printf("Error: Invalid numerator input.\n");
return 1;
}
printf("Enter the denominator: ");
if (scanf("%d", &denominator) != 1) {
printf("Error: Invalid denominator input.\n");
return 1;
}
// Comprehensive division by zero handling
if (denominator == 0) {
printf("Error: Cannot divide by zero. Denominator must be non-zero.\n");
return 1;
}
// Compute and print results with different formats
double fraction_value = (double)numerator / denominator;
printf("\n--- Rational Expression Results ---\n");
printf("Numerator: %d\n", numerator);
printf("Denominator: %d\n", denominator);
printf("Fraction Value: %.2f\n", fraction_value);
printf("Integer Result: %d\n", numerator / denominator);
printf("Remainder: %d\n", numerator % denominator);
return 0;
}
Compile and run the program:
gcc rational_expressions.c -o rational_expressions
./rational_expressions
Example outputs:
Successful computation:
Enter the numerator: 10
Enter the denominator: 4
--- Rational Expression Results ---
Numerator: 10
Denominator: 4
Fraction Value: 2.50
Integer Result: 2
Remainder: 2
Division by zero:
Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero. Denominator must be non-zero.
Invalid input:
Enter the numerator: abc
Error: Invalid numerator input.
Key improvements:
- Added input validation using
scanf()
return value
- Enhanced error messages for different scenarios
- Provided multiple result representations
- Used
double
for more precise floating-point calculations