我有以下 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中最小值的单元格获取同一col中主对角线中单元格的值,主对角线中单元格获取同一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 } };
我的问题是我应该在代码中更改什么以获得原始结果?
求助,谢谢!
最佳答案
你应该写:
mt[index, i] = mt[i, i];
代替:
mt[i, index] = mt[i, i];
关于c# - 替换矩阵 C# 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16761023/