[英]Printing corresponding array index
int diff = gamesA[0] - gamesB[0];
for(int i = 0; i < gamesA.length; i++)
{
int y = Math.abs(gamesA[i] - gamesB[i]);
if(y > diff)
diff = y;
}
System.out.println("In quarter finals, largest deficit of schoolB was "
+ diff + " in the" +_____+ "game.");
I'm trying to print out the index in the array where the largest deficit is.我正在尝试打印出最大赤字所在数组中的索引。 Not what the value but the index it is located at.
不是值是什么,而是它所在的索引。 Anything helps."____" is where the needed code needs to be placed.
任何事情都有帮助。“____”是需要放置所需代码的地方。
Just declare variable to store index outside the loop只需声明变量以在循环外存储索引
int diff = gamesA[0] - gamesB[0];
int index;
for(int i = 0; i < gamesA.length; i++)
{
int y = Math.abs(gamesA[i] - gamesB[i]);
if(y > diff)
diff = y;
index = i;
}
System.out.println("In quarter finals, largest deficit of schoolB was " + diff + " in the" + index + "game.");
In the following way:通过以下方式:
int diff = gamesA[0] - gamesB[0];
int i; // declare it outside the loop to make it available after loop ends.
for(i = 0; i < gamesA.length; i++)
{
int y = Math.abs(gamesA[i] - gamesB[i]);
if(y > diff)
diff = y;
}
System.out.println("In quarter finals, largest deficit of schoolB was "
+ diff + " in the" +(i+1)+ "game.");
//i+1 for indexing from 1 onward .. or use just i for indexing 0 onward.
Other answers so far will always print the last position.到目前为止,其他答案将始终打印最后一个位置。 Try this:-
尝试这个:-
int diff = gamesA[0] - gamesB[0];
int pos = 0;
for (int i = 0; i < gamesA.length; i++) {
int y = Math.abs(gamesA[i] - gamesB[i]);
if (y > diff) {
diff = y;
pos = i;
}
}
System.out.println("In quarter finals, largest deficit of schoolB was "
+ diff + " in the" + pos + "game.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.