ガウスの消去法を用いた連立方程式
sample.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void im_show(int i,double a[][20]);
double fraction(void);
int main(void)
{
int i, j, k, n;
double a[20][20], x[20],p;
double s, q ;
// 方程式(変数)の数を入力
printf("Enter the number of equations : ");scanf("%d", &n);
//分数の有無(y/n)を入力
char yn;
printf("Does the coefficients include any franction (y/n)?");
scanf("%s" , &yn);
if(yn == 'n')
{//分数なし係数入力
printf("\nEnter the coefficients of the equations :\n");
for(i = 0 ; i < n ; i++)
{
printf("----- equation %d -----\n",i+1);
for(j = 0 ; j < n ; j++)
{
printf("a[%d][%d] = ", i + 1, j + 1);
scanf("%lf", &a[i][j]);
}
printf("b[%d] = ", i + 1);
scanf("%lf", &a[i][n]);
printf("\n");
}
}
else if(yn == 'y')
{//分数あり係数入力
printf("\nEnter the coefficients of the equations :\n");
for(i = 0 ; i < n ; i++)
{
printf("----- equation %d -----\n",i+1);
for(j = 0 ; j < n ; j++)
{
printf("a[%d][%d] = ( )/( )\n ", i + 1, j + 1);
a[i][j]=fraction();
printf("a[%d][%d] = %3.2f\n\n", i + 1, j + 1,a[i][j]);
//scanf("%lf", &a[i][j]);
}
printf("b[%d] \n ", i + 1);
a[i][n]=fraction();
printf("b[%d] = %3.2f \n\n ", i + 1,a[i][n]);
//scanf("%lf", &a[i][n]);
printf("\n");
}
}
im_show(n,a);//方程式を表示する関数
for(k=0; k<=n-1; k++)
{
for(i=k+1; i<n; i++)
{
p = a[i][k]/a[k][k];
for(j=k; j<=n; j++)
{
a[i][j] = a[i][j] - (p * a[k][j]);
}
}
}
x[n-1] = a[n-1][n] / a[n-1][n-1];
for(i=n-2; i>=0; i--)
{
s=0;
for(j=i+1; j<n; j++)
{
s += (a[i][j]*x[j]);
x[i] = (a[i][n]-s)/a[i][i];
}
}
//結果を表示
printf("\nThe result is :\n");
for(i = 0 ; i < n ; i++)printf("\nx[%d] = %f", i + 1, x[i]);
printf("\n");
return 0;
}
//分数処理
double fraction(void){
double numerator,denominator;
printf("Enter numerator first>_\n");
scanf(" %lf",&numerator);
printf("-\n");
scanf(" %lf",&denominator);printf("\n");
return numerator/denominator;
}
//入力した連立方程式を表示
void im_show(int i,double a[][20]){
int m,n;
int k;
printf("\nsimultaneous equations:\n\n");
for(m=0;m<i;++m){
k=0;
for(n=0;n<i;++n){
k+=1;
printf("%3.2f", a[m][n]);printf(" x[%d]",k);
if(k<i)printf(" + ");
else if(n==i-1)
printf(" = %3.2f \n",a[m][i]);
}
}
//それっぽいので5秒遅延させる
printf("\n\nCalculating:\n");
int count;
for(count=0;count<101;count++){
if(i*count %31 ==0)sleep(1);
printf("%d %% \r",count);
}
printf("\n");
}
terminal実行結果
C>gcc sample.c
C>.\a.exe
Enter the number of equations : 2
Does the coefficients include any franction (y/n)?n
Enter the coefficients of the equations :
----- equation 1 -----
a[1][1] = 2
a[1][2] = 1
b[1] = 7
----- equation 2 -----
a[2][1] = 3
a[2][2] = -1
b[2] = 3
simultaneous equations:
2.00 x[1] + 1.00 x[2] = 7.00
3.00 x[1] + -1.00 x[2] = 3.00
Calculating:
100 %
The result is :
x[1] = 2.000000
x[2] = 3.000000