解または特殊ケースを表示する
この最後のステップでは、2 つの一次方程式の連立方程式におけるさまざまなタイプの解に対して、より詳細な出力を提供するようにプログラムを強化します。
既存のファイルを開き、最終的な修正を行います。
cd ~/project
nano linear_equations.c
出力形式を改善したコードに更新します。
#include <stdio.h>
#include <math.h>
// 行列式を計算する関数
float determinant(float a1, float b1, float a2, float b2) {
return a1 * b2 - a2 * b1;
}
int main() {
float a1, b1, c1; // 最初の方程式の係数
float a2, b2, c2; // 2 番目の方程式の係数
float det, detX, detY;
float x, y;
float EPSILON = 1e-6; // 浮動小数点数の比較用の小さな値
// 最初の方程式の係数を入力して読み取る
printf("Linear Equation Solver\n");
printf("Enter coefficients for the first equation (ax + by = c):\n");
printf("a1: ");
scanf("%f", &a1);
printf("b1: ");
scanf("%f", &b1);
printf("c1: ");
scanf("%f", &c1);
// 2 番目の方程式の係数を入力して読み取る
printf("Enter coefficients for the second equation (ax + by = c):\n");
printf("a2: ");
scanf("%f", &a2);
printf("b2: ");
scanf("%f", &b2);
printf("c2: ");
scanf("%f", &c2);
// 入力された方程式を表示する
printf("\nInput Equations:\n");
printf("Equation 1: %.2fx + %.2fy = %.2f\n", a1, b1, c1);
printf("Equation 2: %.2fx + %.2fy = %.2f\n", a2, b2, c2);
// 主行列式を計算する
det = determinant(a1, b1, a2, b2);
// 解のタイプを判断して表示する
if (fabs(det) > EPSILON) {
// 一意の解のケース
detX = determinant(c1, b1, c2, b2);
detY = determinant(a1, c1, a2, c2);
x = detX / det;
y = detY / det;
printf("\n--- Solution Type: Unique Solution ---\n");
printf("Solution:\n");
printf("x = %.2f\n", x);
printf("y = %.2f\n", y);
} else {
// 解がないか、無数の解があるかをチェックする
detX = determinant(c1, b1, c2, b2);
detY = determinant(a1, c1, a2, c2);
if (fabs(detX) > EPSILON || fabs(detY) > EPSILON) {
printf("\n--- Solution Type: No Solution ---\n");
printf("The system of equations has no solution.\n");
printf("Equations are inconsistent and parallel.\n");
} else {
printf("\n--- Solution Type: Infinite Solutions ---\n");
printf("The system of equations has infinitely many solutions.\n");
printf("Equations are equivalent and dependent.\n");
}
}
return 0;
}
プログラムをコンパイルして実行します。
gcc linear_equations.c -o linear_equations
./linear_equations
一意の解の出力例:
Linear Equation Solver
Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 1
b2: 4
c2: 10
Input Equations:
Equation 1: 2.00x + 3.00y = 8.00
Equation 2: 1.00x + 4.00y = 10.00
--- Solution Type: Unique Solution ---
Solution:
x = 2.00
y = 2.00
解がない場合の出力例:
Linear Equation Solver
Enter coefficients for the first equation (ax + by = c):
a1: 2
b1: 3
c1: 8
Enter coefficients for the second equation (ax + by = c):
a2: 4
b2: 6
c2: 16
Input Equations:
Equation 1: 2.00x + 3.00y = 8.00
Equation 2: 4.00x + 6.00y = 16.00
--- Solution Type: No Solution ---
The system of equations has no solution.
Equations are inconsistent and parallel.