用c++编写顺序消元法和列主元消元法的程序求解线性方程组的程序
时间: 2023-06-05 08:05:34 浏览: 150
非常感谢您的问题。这是一个技术问题,我可以为您提供一些帮助。
以下是用 C 编写顺序消元法和列主元消元法的程序求解线性方程组的代码示例:
顺序消元法:
```
#include <stdio.h>
#define N 3
int main()
{
int i, j, k;
float A[N][N+1], x[N];
/* Input */
printf("Enter the coefficients of the equations: \n");
for(i=0; i<N; i++)
{
printf("Equation %d: ", i+1);
for(j=0; j<=N; j++)
scanf("%f", &A[i][j]);
}
/* Forward Elimination */
for(k=0; k<N-1; k++)
{
for(i=k+1; i<N; i++)
{
float factor = A[i][k]/A[k][k];
for(j=k+1; j<=N; j++)
A[i][j] -= factor*A[k][j];
}
}
/* Backward Substitution */
for(i=N-1; i>=0; i--)
{
float sum = A[i][N];
for(j=i+1; j<N; j++)
sum -= A[i][j]*x[j];
x[i] = sum/A[i][i];
}
/* Output */
printf("\nThe solution is: \n");
for(i=0; i<N; i++)
printf("x%d = %.2f\n", i+1, x[i]);
return 0;
}
```
列主元消元法:
```
#include <stdio.h>
#define N 3
int main()
{
int i, j, k;
float A[N][N+1], x[N], temp[N+1];
/* Input */
printf("Enter the coefficients of the equations: \n");
for(i=0; i<N; i++)
{
printf("Equation %d: ", i+1);
for(j=0; j<=N; j++)
scanf("%f", &A[i][j]);
}
/* Forward Elimination */
for(k=0; k<N-1; k++)
{
float max = A[k][k];
int index = k;
for(i=k+1; i<N; i++)
{
if(A[i][k]>max)
{
max = A[i][k];
index = i;
}
}
if(index!=k)
{
for(j=k; j<=N; j++)
{
temp[j] = A[k][j];
A[k][j] = A[index][j];
A[index][j] = temp[j];
}
}
for(i=k+1; i<N; i++)
{
float factor = A[i][k]/A[k][k];
for(j=k+1; j<=N; j++)
A[i][j] -= factor*A[k][j];
}
}
/* Backward Substitution */
for(i=N-1; i>=0; i--)
{
float sum = A[i][N];
for(j=i+1; j<N; j++)
sum -= A[i][j]*x[j];
x[i] = sum/A[i][i];
}
/* Output */
printf("\nThe solution is: \n");
for(i=0; i<N; i++)
printf("x%d = %.2f\n", i+1, x[i]);
return 0;
}
```
希望能对您有所帮助。如果您有任何疑问或需要进一步的帮助,请随时联系我。
阅读全文