■ n 元連立1次方程式の解(平成18年秋午後問3)
/*
* 基本情報技術者
* 平成18年秋午後問3
*
* n 元連立1次方程式の解
*
*/
#include <stdio.h>
#define N 3
void Gauss(int n, double a[][N+1], double b[], double x[])
{
int i, j, k;
double Pivot, Factor, Sum;
/* 前進消去 */
for (k = 1; k <= n - 1; k++) {
Pivot = a[k][k];
for (i = k + 1; i <= n; i++) {
Factor = a[i][k] / Pivot;
for (j = k + 1; j <= n; j++)
a[i][j] = a[i][j] - a[k][j] * Factor;
b[i] = b[i] - b[k] * Factor;
}
}
/* 後退代入 */
x[n] = b[n] / a[n][n];
for (i = n - 1; i >= 1; i--) {
Sum = 0.0;
for (j = i + 1; j <= n; j++)
Sum = Sum + a[i][j] * x[j];
x[i] = (b[i] - Sum) / a[i][i];
}
}
int main()
{
double a[N+1][N+1] = {{ 0, 0, 0, 0 },
{ 0, 2, 1, 2 },
{ 0, 3, 2, 1 },
{ 0, 2, 4, 1 }};
double b[N+1] = { 0, 2, 6, 9 };
double x[N+1];
int i;
Gauss(N, a, b, x);
for (i = 1; i <= N; i++)
printf("x%d = %4.1f\n", i, x[i]);
return 0;
}