Вывод действительных или комплексных решений
На этом этапе вы улучшите программу - решатель квадратных уравнений, чтобы она давала более подробный вывод и обрабатывала различные типы решений с улучшенным форматированием.
Откройте существующий файл и обновите код:
cd ~/project
nano quadratic_solver.c
Замените предыдущий код следующим:
#include <stdio.h>
#include <math.h>
void printQuadraticSolutions(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
printf("Quadratic Equation: %.2fx² + %.2fx + %.2f = 0\n", a, b, c);
printf("Discriminant: %.2f\n", discriminant);
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Solution Type: Two Distinct Real Roots\n");
printf("Root 1: %.2f\n", root1);
printf("Root 2: %.2f\n", root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
printf("Solution Type: One Real Root (Repeated)\n");
printf("Root: %.2f\n", root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Solution Type: Complex Conjugate Roots\n");
printf("Root 1: %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2: %.2f - %.2fi\n", realPart, imaginaryPart);
}
}
int main() {
double a, b, c;
printf("Quadratic Equation Solver\n");
printf("------------------------\n");
printf("Enter coefficient a: ");
scanf("%lf", &a);
printf("Enter coefficient b: ");
scanf("%lf", &b);
printf("Enter coefficient c: ");
scanf("%lf", &c);
printf("\n");
printQuadraticSolutions(a, b, c);
return 0;
}
Скомпилируйте программу:
gcc quadratic_solver.c -o quadratic_solver -lm
Запустите программу в различных сценариях:
./quadratic_solver
Пример вывода (два действительных корня):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
Quadratic Equation: 1.00x² + -5.00x + 6.00 = 0
Discriminant: 1.00
Solution Type: Two Distinct Real Roots
Root 1: 3.00
Root 2: 2.00
Пример вывода (один действительный корень):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1
Quadratic Equation: 1.00x² + -2.00x + 1.00 = 0
Discriminant: 0.00
Solution Type: One Real Root (Repeated)
Root: 1.00
Пример вывода (комплексные корни):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Quadratic Equation: 1.00x² + 2.00x + 5.00 = 0
Discriminant: -16.00
Solution Type: Complex Conjugate Roots
Root 1: -1.00 + 2.00i
Root 2: -1.00 - 2.00i
Основные улучшения:
- Создана отдельная функция
printQuadraticSolutions()
для лучшей организации кода.
- Добавлен более описательный вывод с указанием типа решения и деталями уравнения.
- Сохранена та же логика вычисления корней, что и на предыдущем этапе.
- Улучшено пользовательское интерфейс с заголовком и четким форматированием.