2013-02-16 104 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