多维数组-如何在c#中找到矩阵3x3的det

本文关键字:3x3 det 数组 | 更新日期: 2023-09-27 17:59:53

我可以使用以下代码找到矩阵2x2的det:

using System;
class find_det
{
static void Main()
{
    int[,] x = { { 3, 5, }, { 5, 6 }, { 7, 8 } };
    int det_of_x = x[0, 0] * x[1, 0] * x[0, 1] * x[1, 1];
    Console.WriteLine(det_of_x);
    Console.ReadLine();
}
}

但当我试图找到3x3矩阵的det时,使用这个代码:

using System;
class matrix3x3
{
    static void Main()
{
    int[,,] x={{3,4,5},{3,5,6},{5,4,3}};
    int det_of_x=x[0,0]*x[0,1]*x[0,2]*x[1,0]*x[1,1]*x[1,2]*x[2,0]*x[2,1]*x[2,2];
    Console.WriteLine(det_of_x);
    Console.ReadLine();
    }
}

它出错了。为什么?

多维数组-如何在c#中找到矩阵3x3的det

您在第二个示例中声明了一个3D数组,而不是3x3 2D数组。从声明中删除多余的","。

它仍然是二维数组(int[,])而不是三维数组(int[,,])。

int[,] x = { { 3, 4, 5 }, { 3, 5, 6 }, { 5, 4, 3 } };

旁注:你可以对任何多维数组进行这样的计算:

int det_of_x = 1;
foreach (int n in x) det_of_x *= n;

因为您有一个三维数组,并且像使用二维数组(如x[0,0])一样使用它。

您声明的是一个静态二维数组。对于2D阵列,您可以这样使用它;

int[,] x = { { 3, 4, 5 }, { 3, 5, 6 }, { 5, 4, 3 } };
int det_of_x = x[0, 0] * x[0, 1] * x[0, 2] * x[1, 0] * x[1, 1] * x[1, 2] * x[2, 0] * x[2, 1] * x[2, 2];
Console.WriteLine(det_of_x);
Console.ReadLine();

如果你想使用三维阵列,你应该像int[, ,] 一样使用它

查看MSDN中有关Multidimensional Arrays的更多信息。

由于数组实现了IEnumerableIEnumerable<T>,因此可以在C#中的所有数组上使用foreach迭代。在您的情况下,您可以这样使用它;

int[, ,] x = new int[,,]{ {{ 3, 4, 5 }, { 3, 5, 6 }, { 5, 4, 3 }} };
int det_of_x = 1;
foreach (var i in x)
{
    det_of_x *= i;
}
Console.WriteLine(det_of_x); // Output will be 324000

这是一个DEMO