【问题标题】:Replace values in matrix C#替换矩阵 C# 中的值
【发布时间】:2013-05-26 15:59:31
【问题描述】:

我有以下 C# 代码:

int[,] mt = { { 5, 4, 6, 2 }, { 8, 1, 5, 4 }, { 2, 3, 8, 6 }, { 9, 6, 1, 8 } };
        int i, min, index, j, v;
        for (i = 0; i < mt.GetLength(1); i++)
        {
            index = 0;
            min = int.MaxValue;
            for (j = 0; j < mt.GetLength(0); j++)
            {
                v = mt[j, i];
                if (v < min)
                { min = mt[j, i]; index = j; }
            }
            mt[i, index] = mt[i, i]; mt[i, i] = min;

        }
        for (i = 0; i < mt.GetLength(0); i++)
        {//print the matrix after changes
            for (j = 0; j < mt.GetLength(1); j++)
                Console.Write("{0,3}", mt[i, j]);
            Console.WriteLine();
        }
        Console.ReadLine();

这段代码应该做的是用主对角线的同一列中的值替换每个列中的最小值(这是二次矩阵)。

所以col中值最小的单元格获取同列中主对角线中单元格的值,主对角线中的单元格获取同列中编号最小的单元格的值。

我尝试了上面的代码,但我得到了这个结果:

{ { 2, 4, 5, 2 }, { 4, 1, 3, 6 }, { 5, 5, 1, 1 }, { 2, 4, 8, 2 } };

这是我应该得到的:

   { { 2, 4, 6, 8 }, { 8, 1, 5, 4 }, { 2, 3, 1, 8 }, { 8, 6, 1, 2 } };

我的问题是我应该在代码中进行哪些更改才能获得 idial 结果?

希望得到帮助,谢谢!

【问题讨论】:

    标签: c# arrays matrix


    【解决方案1】:

    你应该写:

    mt[index, i] = mt[i, i]; 
    

    代替:

    mt[i, index] = mt[i, i];
    

    【讨论】:

    • 嗨,非常感谢你,我犯了这么愚蠢的错误!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多