如何在c#中找到矩阵3x3的det

时间:2013-02-16 13:22:32

标签: c# multidimensional-array

我能够使用以下代码找到矩阵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 Matrix的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();
    }
}

它出错了。为什么呢?

4 个答案:

答案 0 :(得分:2)

它仍然是一个二维数组(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;

答案 1 :(得分:2)

您已在第二个示例中声明了一个3D数组,而不是一个3x3 2D数组。从声明中删除额外的“,”。

答案 2 :(得分:1)

因为你有一个三维数组,并且像二维一样使用它,例如x[0,0]

答案 3 :(得分:1)

你宣称它是一个二维数组。对于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