2013-02-16 101 views
-1

我能够使用这个代码,找出矩阵2×2的DET:如何找到在C#矩阵3×3的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(); 
    } 
} 

它出错。为什么?

+0

什么是错误? – 2013-02-16 13:26:17

+0

你确定你计算行列式吗? – qben 2013-02-16 13:27:27

+2

可怕的模糊问题。编译器的错误应该让你知道这里有什么问题。但正如其他人所说的那样,它仍然是一个二维阵列,而不是一个3D,在类型中删除额外的。 – 2013-02-16 13:27:45

回答

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; 
+0

Damnn,我认为2d矩阵是2x2,而3d是3x3。感谢您的时间。我解决了问题。 – user2078395 2013-02-16 14:11:52

1

因为你有一个3维数组并使用它像一个二维的,如x[0,0]

2

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

1

你声称它还是一个二维数组。对于二维数组,你可以像这样使用它;

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(); 

如果您想使用3维数组,你应该使用它像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