[英]How to find the location of maximum and minimum value of a 2d array
我不知道我是否清楚这个,但我已经有了最小和最大的打印权,但我似乎无法弄清楚如何说出它们所在的确切行和列。这就是我的意思到目前为止;
double max = m[0][0];
double min = m[0][0];
System.out.println("The matrix is : ");
for(int i = 0; i < m.length; i++)
{
for ( int j = 0; j < m[i].length; j++ )
{
System.out.printf(" " + "%6.1f " , m[i][j]);
if (m[i][j] > max)
max = m [i][j];
else if
(m[i][j] < min)
min = m [i][j];
我怎样才能说出他们的位置? 例如:(“最大数字在第1行,第2列”)类似的东西...我真的很感激任何帮助
请参阅以下修改。 我添加了变量来跟踪最小值和最大值的索引。 在循环结束时,您可以简单地打印出maxIndex1
, maxIndex2
, minIndex1
和minIndex2
。
double max = m[0][0];
double min = m[0][0];
//declare variables to track the indices of the min and max
int maxIndex1 = -1;
int maxIndex2 = -1;
int minIndex1 = -1;
int minIndex2 = -1;
System.out.println("The matrix is : ");
for(int i = 0; i < m.length; i++)
{
for ( int j = 0; j < m[i].length; j++ )
{
System.out.printf(" " + "%6.1f " , m[i][j]);
if (m[i][j] > max)
{
max = m [i][j];
//record the indices of the new max
maxIndex1 = i;
maxIndex2 = j;
}
else if (m[i][j] < min)
{
min = m [i][j];
//record the indices of the new min
minIndex1 = i;
minIndex2 = j;
}
请注意,如果您有两个相等且值与数组中的最大值相关联的值,则只会记录其中一个值。 如果您想记录最小/最大的所有联系的位置,您可以更改此项以保存坐标列表而不是单个坐标。
这很容易! 只需声明另外两个变量来存储x和y坐标。 并在if和else中更新它们(不要忘记在if和else子句中添加花括号!)并且你拥有它们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.