用c#写一个解线性方程的程序
时间: 2023-09-10 22:13:35 浏览: 120
以下是一个用 C# 编写的解线性方程组的程序:
```csharp
using System;
class LinearEquationSolver
{
static void Main()
{
Console.WriteLine("请输入线性方程组的系数矩阵和常数矩阵(以空格分隔):");
double[][] matrix = new double[3][];
for (int i = 0; i < 3; i++)
{
string input = Console.ReadLine();
string[] values = input.Split(' ');
matrix[i] = new double[4];
for (int j = 0; j < 4; j++)
{
matrix[i][j] = double.Parse(values[j]);
}
}
double detA = matrix[0][0] * matrix[1][1] * matrix[2][2]
+ matrix[0][1] * matrix[1][2] * matrix[2][0]
+ matrix[0][2] * matrix[1][0] * matrix[2][1]
- matrix[0][0] * matrix[1][2] * matrix[2][1]
- matrix[0][1] * matrix[1][0] * matrix[2][2]
- matrix[0][2] * matrix[1][1] * matrix[2][0];
if (detA == 0)
{
Console.WriteLine("系数矩阵的行列式为 0,无解。");
return;
}
double[] result = new double[3];
for (int i = 0; i < 3; i++)
{
double[][] tempMatrix = new double[3][];
for (int j = 0; j < 3; j++)
{
tempMatrix[j] = new double[3];
for (int k = 0; k < 3; k++)
{
tempMatrix[j][k] = matrix[j][k];
}
tempMatrix[j][i] = matrix[j][3];
}
double detTemp = tempMatrix[0][0] * tempMatrix[1][1] * tempMatrix[2][2]
+ tempMatrix[0][1] * tempMatrix[1][2] * tempMatrix[2][0]
+ tempMatrix[0][2] * tempMatrix[1][0] * tempMatrix[2][1]
- tempMatrix[0][0] * tempMatrix[1][2] * tempMatrix[2][1]
- tempMatrix[0][1] * tempMatrix[1][0] * tempMatrix[2][2]
- tempMatrix[0][2] * tempMatrix[1][1] * tempMatrix[2][0];
result[i] = detTemp / detA;
}
Console.WriteLine("线性方程组的解为:");
Console.WriteLine("x = " + result[0]);
Console.WriteLine("y = " + result[1]);
Console.WriteLine("z = " + result[2]);
}
}
```
这个程序是一个控制台程序,它会提示用户输入一个 3x4 的矩阵,其中前三列是系数矩阵,最后一列是常数矩阵。程序先计算系数矩阵的行列式,如果为 0 则无解;否则,对于每个未知数,构造一个新的 3x3 矩阵并计算它的行列式,最后求出未知数的值。程序输出每个未知数的值。