如何使用C#程序找到具有最高值的行和列?该程序要求用户输入程序中有多少行和多少列,然后要求输入数字。假设我在矩阵中放入4列和3行,然后输入以下数字:
89 11 22 44
29 51 80 20
33 10 45 10
在这种情况下,我需要的输出将是“第一个最大值位于行1和列1”。我如何使程序查找最大值所在的位置,直到该程序打印出最大值所在的行和列。当我尝试调用该方法以获取返回值时,它不会打印出来。这是我尝试的代码:
using System;
namespace locateLargest
{
class Program
{
static void Main(string[] args)
{
int[,] arrayPart1 = new int[3, 4];
for (int row = 0; row < arrayPart1.GetLength(0); row++)
{
for (int column = 0; column < arrayPart1.GetLength(1); column++)
{
arrayPart1[row, column] = Convert.ToInt32(Console.ReadLine());
}
}
for (int row = 0; row < arrayPart1.GetLength(0); row++)
{
for (int column = 0; column < arrayPart1.GetLength(1); column++)
{
Console.Write("Value at [" + row + ", " + column + "]: " + arrayPart1[row, column] + "\t");
}
Console.WriteLine();
Console.WriteLine("The highest value in the array is at "+largest)
}
}
public static int[] LocateLargest(int[,] someArray)
{
{
int largest = someArray[0, 0];
int row, column;
int maxRow = 0;
int maxCol = 0;
for (row = 0; row < someArray.GetLength(0); row++)
{
for (column = 0; column < someArray.GetLength(1); column++)
{
if (someArray[row, column] > largest)
{
maxRow = row;
maxCol = column;
largest = someArray[row, column];
}
}
}
return largest;
}
}
}
}
答案 0 :(得分:1)
我认为这是初学者最简单的方法。
static void Main(string[] args)
{
int[,] arrayPart1 = new int[3, 4];
for (int row = 0; row < arrayPart1.GetLength(0); row++)
{
for (int column = 0; column < arrayPart1.GetLength(1); column++)
{
arrayPart1[row, column] = Convert.ToInt32(Console.ReadLine());
}
}
for (int row = 0; row < arrayPart1.GetLength(0); row++)
{
for (int column = 0; column < arrayPart1.GetLength(1); column++)
{
Console.Write("Value at [" + row + ", " + column + "]: " + arrayPart1[row, column] + "\t");
}
Console.WriteLine();
Console.WriteLine("The highest value in the array is at "+ LocateLargest (arrayPart1)).ToString ())
}
}
int LocateLargest(int[,] someArray)
{
int largest = someArray[0, 0];
int row, column;
int maxRow = 0;
int maxCol = 0;
for (row = 0; row < someArray.GetLength(0); row++)
{
for (column = 0; column < someArray.GetLength(1); column++)
{
if (someArray[row, column] > largest)
{
maxRow = row;
maxCol = column;
largest = someArray[row, column];
}
}
Console.WriteLine("The largest value is at row " + maxRow.ToString() + "and column " + maxCol.ToString());
return largest;
}
答案 1 :(得分:0)
这对我有用:
var input = new []
{
"89 11 22 44",
"29 51 80 20",
"33 10 45 10",
};
var result =
input
.Select((line, row) => new
{
row,
columns =
line
.Split(' ')
.Select((number, column) => new
{
column,
value = int.Parse(number)
})
})
.SelectMany(x => x.columns, (x, y) => new { x.row, y.column, y. value })
.OrderByDescending(x => x.value)
.First();
Console.WriteLine($"The largest value is {result.value} at row {result.row + 1} and column {result.column + 1}");
它给出:
第一行和第一列的最大值为89