//高斯顺序消元法
#include<stdlib.h>
#include<stdio.h>
#define N 10
void gauss_shunxu(float a[N][N],float h[N]){
int i,j,k;
float x[N],temp1,temp2;
for(k=0; k<N-1; k++){
for(i=k + 1; i<N; i++){
temp1=a[i][k]/a[k][k];
h[i]-= h[k]*temp1;
for(j=k+1; j<N; j++){
a[i][j]-=a[k][j]*temp1;
}
}
}
x[N-1]=h[N-1]/a[N-1][N-1];
for(i=N-2; i>-1; i--){
temp2=0;
for(j=i+1; j<N; j++){
temp2+=a[i][j]*x[j];
}
x[i]=(h[i]-temp2)/a[i][i];
}
printf("该线性方程组用Gauss顺序消元法求得的解为:\n");
for(i=0; i<N; i++){
printf("x%d=%lf\n",i+1,x[i]);
}
}
void main() {
float a[N][N]= {{4,2,-3,-1,2,1,0,0,0,0},
{8,6,-5,-3,6,5,0,1,0,0},
{4,2,-2,-1,3,2,-1,0,3,1},
{0,-2,1,5,-1,3,-1,1,9,4},
{-4,2,6,-1,6,7,-3,3,2,3},
{8,6,-8,5,7,17,2,6,-3,5},
{0,2,-1,3,-4,2,5,3,0,1},
{16,10,-11,-9,17,34,2,-1,2,2},
{4,6,2,-7,13,9,2,0,12,4},
{0,0,-1,8,-3,-24,-8,6,3,-1}};
float h[N]= {5,12,3,2,3,46,13,38,19,-21};
gauss_shunxu(a,h);
}
运行截图:
#include
#include
#include
extern int flag=1;
int pingfanggenfa(double **a,double *b,int H)
{
double *y = (double *) malloc(sizeof(double)*H);
double s;
int i,j,k;
a[0][0] = sqrt(a[0][0]);
for (i = 1; i < H; i++)
a[i][0] = a[i][0] / a[0][0];
for (k = 1; k < H; k++)
{
for (i = k; i < H; i++)
{
for (s = 0, j = 0; j < k; j++)
s += a[i][j] * a[k][j];
if (i > k)
a[i][k] = (a[i][k] - s) / a[k][k];
else if (i == k)
a[i][k] = sqrt(a[i][k] - s);
}
}
for(j = 0 ; j < H ; j++)
for(i = j+1 ; i < H ; i++)
a[j][i] = a[i][j];
for(i = 0 ,flag = 0 ; i < H ; j++)
{
if(a[i][i] == 0)
{
printf("方程系数输入有误\n");
flag = 1 ;
}break;
}
if(flag != 1){
y[0]= b[0] / a[0][0];
for (k = 0; k < H; k++)
{
for (s = 0, j = 0; j < k; j++)
s += a[k][j] * y[j];
y[k] = (b[k] - s) / a[k][k];
}
b[H-1]= y[H-1] / a[H-1][H-1];
for (k = H-2; k >= 0; k--)
{
for (s = 0, j = k+1; j < H; j++)
s += a[j][k] * b[j];
b[k] = (y[k] - s) / a[k][k];
}
printf("\nL的下三角矩阵为:\n");
for(i = 0 ; i < H ; i++)
{
for(k = 0 ; k <= i ; k++)
printf("%lf ",a[i][k]);
printf("\n");
}
printf("\nL的转置矩阵为:\n");
for(j = 0 ; j< H ; j++)
{
for(i = 0 ; i < H ; i++)
{
if(i < j)
printf(" ");
else
printf("%lf ",a[i][j]);
}
printf("\n");
}
printf("\nY的值为:\n");
for(i = 0 ; i < H ; i++)
printf("y%d=%lf\n",i+1,y[i]);
printf("\nX的值为:\n");
for(i = 0 ; i < H ; i++)
printf("x%d=%lf\n",i+1,b[i]);
free(y);
return 0;
}
else if(flag == 1)
flag = 1;
return 0;
}
int main(){
double **a , *b;
int i, j , H;
while(flag == 1)
{
printf("请输入未知数个数n:\n");
scanf("%d", &H);
a = (double**)malloc(sizeof(double*)*H);
b = (double *) malloc(sizeof(double)*H);
for (i = 0; i < H; i++)
a[i] = (double*)malloc(sizeof(double)*H);
printf("请输入系数矩阵:\n");
for (i = 0; i < H; i++){
for (j = 0; j < H; j++)
scanf("%lf",&a[i][j]);
}
printf("请输入向量b:\n");
for (i = 0; i < H; i++){
scanf("%lf",&b[i]);
}
pingfanggenfa(a,b,H);
}
free(b);
for (i = 0; i < H; ++i)
free(a[i]);
free(a);
}
运行截图: