Print the Solution or State No Solution
In this final step, you will enhance the linear equation solver to handle different scenarios and provide clear output for the solution.
Open the previous file and update the code:
cd ~/project
nano linear_equation.c
Replace the contents with the following code:
#include <stdio.h>
#include <math.h>
int main() {
double a, b, x;
// Prompt user to enter coefficient a
printf("Enter coefficient a: ");
scanf("%lf", &a);
// Prompt user to enter coefficient b
printf("Enter coefficient b: ");
scanf("%lf", &b);
// Check different scenarios
if (a == 0 && b == 0) {
printf("Infinite solutions: Every real number is a solution.\n");
} else if (a == 0 && b != 0) {
printf("No solution: The equation cannot be solved.\n");
} else {
// Compute solution x
x = -b / a;
// Print the solution
printf("Equation: %.2fx + %.2f = 0\n", a, b);
printf("Solution: x = %.2f\n", x);
}
return 0;
}
Compile and run the program:
gcc linear_equation.c -o linear_equation
./linear_equation
Example output scenarios:
Scenario 1 (Normal solution):
Enter coefficient a: 2
Enter coefficient b: 4
Equation: 2.00x + 4.00 = 0
Solution: x = -2.00
Scenario 2 (No solution):
Enter coefficient a: 0
Enter coefficient b: 5
No solution: The equation cannot be solved.
Scenario 3 (Infinite solutions):
Enter coefficient a: 0
Enter coefficient b: 0
Infinite solutions: Every real number is a solution.
Key improvements in this version:
- Handles three distinct scenarios for linear equations
- Provides clear, informative messages for different cases
- Uses precise mathematical logic to determine solution type