C语言程序设计:线性方程组求解

2025-03-27 00:01:31
推荐回答(4个)
回答1:

程序能成功运行,用的高斯消元法
不过没有给出菜单
输入提示信息比较清楚
某次的结果如下:
你要解几元线性方程组:
2
请输入第1行相应的系数:
a[0][0]: 2
a[0][1]: -1
请输入第1行相应的常数:
b[0]: 3
请输入第2行相应的系数:
a[1][0]: 1
a[1][1]: 1
请输入第2行相应的常数:
b[1]: 9
方程组:
2.000000X1 - X2= 3.000000
X1 + X2= 9.000000
该方程组的解为:
x1 = 4.00
x2 = 5.00
Press any key to continue

程序如下:

#include
#include
#include
#include

int GS(int,double**,double *,double);
double **TwoArrayAlloc(int,int);
void TwoArrayFree(double **);

void main()
{
int i,j,n;
double ep,**a,*b;
ep = 1e-4;
printf("你要解几元线性方程组:\n");
scanf("%d",&n);
a = TwoArrayAlloc(n,n);
b = (double *)calloc(n,sizeof(double));
if(b == NULL)
{
printf("内存分配失败\n");
exit(1);
}

for(i=0;i{
printf("请输入第%d行相应的系数:\n",i+1);
for(j=0;j{
printf("a[%d][%d]: ",i,j);
scanf("%lf",a[i]+j);
fflush(stdin);
}
printf("请输入第%d行相应的常数:\n",i+1);
printf("b[%d]: ",i);
scanf("%lf",b+i);
fflush(stdin);
}
printf("方程组:\n");
for(i=0;i{
for(j=0;j{
if(a[i][j]>0)
{
if(j>0)printf(" + ");
if(a[i][j]!=1)
printf("%lfX%d",a[i][j],j+1);
else
printf("X%d",j+1);

}
if(a[i][j]<0)
{
if(j>0)printf(" - ");
if(a[i][j]!=-1)
printf("%lfX%d",fabs(a[i][j]),j+1);
else
printf("X%d",j+1);
}

}
printf("= %lf\n",b[i]);
}

if(!GS(n,a,b,ep))
{
printf("不可以用高斯消去法求解\n");
exit(0);
}
printf("该方程组的解为:\n");
for(i=0;iprintf("x%d = %.2f\n",i+1,b[i]);
TwoArrayFree(a);
free(b);
}

int GS(int n,double **a,double *b,double ep)
{
int i,j,k,l;
double t;
for(k=1;k<=n;k++)
{
for(l=k;l<=n;l++)
if(fabs(a[l-1][k-1])>ep)
break;
else if(l==n)
return(0);
if(l!=k)
{
for(j=k;j<=n;j++)
{
t = a[k-1][j-1];
a[k-1][j-1]=a[l-1][j-1];
a[l-1][j-1]=t;
}
t=b[k-1];
b[k-1]=b[l-1];
b[l-1]=t;
}
t=1/a[k-1][k-1];
for(j=k+1;j<=n;j++)
a[k-1][j-1]=t*a[k-1][j-1];
b[k-1]*=t;
for(i=k+1;i<=n;i++)
{
for(j=k+1;j<=n;j++)
a[i-1][j-1]-=a[i-1][k-1]*a[k-1][j-1];
b[i-1]-=a[i-1][k-1]*b[k-1];
}
}
for(i=n-1;i>=1;i--)
for(j=i+1;j<=n;j++)
b[i-1]-=a[i-1][j-1]*b[j-1];
return(1);
}

double **TwoArrayAlloc(int r,int c)
{
double *x,**y;
int n;
x=(double *)calloc(r*c,sizeof(double));
y=(double **)calloc(r,sizeof(double*));
if(!x||!y)
{
printf("内存分配失败\n");
exit(1);
}
for(n=0;n<=r-1;++n)
y[n]=&x[c*n];
return (y);
}

void TwoArrayFree(double **x)
{
free(x[0]);
free(x);
}

回答2:

找MATLAB吧,C不是用来做矩阵运算的...
光求矩阵的逆这一项就要用很长篇幅的C代码描述,何况你还要求图形界面和菜单设计

回答3:

循环嵌套 把对角线元素互换

回答4:

赶得上个的