【问题标题】:How to find det of matrix 3x3 in c#如何在c#中找到矩阵3x3的det
【发布时间】:2013-02-16 13:22:31
【问题描述】:

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

出现错误。为什么?

【问题讨论】:

  • 您确定要计算行列式吗?
  • 非常模糊的问题。你的编译器的错误应该至少给你一个提示,这里有什么问题。但正如其他人所说,它仍然是 2D Array,而不是 3D,删除类型中的额外 , 。
  • 我不知道你在计算什么,但它也不是矩阵的行列式。 2x2 矩阵 A 的行列式是 det(A) = a11*a22 - a12*a21。

标签: c# multidimensional-array


【解决方案1】:

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

【讨论】:

    【解决方案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;
    

    【讨论】:

    • 该死的,我认为 2d 矩阵是 2x2 而 3d 是 3x3。感谢您的时间。我解决了问题。
    【解决方案3】:

    因为您有一个 3 维数组,并且像使用 2 维数组一样使用它,例如 x[0,0]。

    【讨论】:

      【解决方案4】:

      你声明的仍然是二维数组。对于二维数组,您可以像这样使用它;

      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 的更多信息。

      由于数组实现了IEnumerable 和IEnumerable<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。

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多