実数解または複素数解を出力する
このステップでは、二次方程式の求解プログラムを拡張して、より詳細な出力を提供し、異なる解のタイプをより適切な書式で扱います。
既存のファイルを開き、コードを更新します。
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
出力例(2 つの実数解):
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
出力例(1 つの実数解):
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()
を作成しました。
- 解のタイプと方程式の詳細を含む、より説明的な出力を追加しました。
- 前のステップと同じ解の計算ロジックを維持しました。
- タイトルと明確な書式でユーザーインターフェイスを改善しました。