在Java中打印数组的索引
如何在Java中打印数组的索引? 我真的被这个困扰了,我觉得应该是一个if语句
if (i == 5050) {
System.out.println("Index is: " +i);
}
我真的很感激任何帮助,即使这只是一个开始寻找答案的好地方。 谢谢
public class summation {
public static void main(String[] args) {
long[] a = new long[101];
long sum;
int i, numbers;
numbers = 100;
// initialise the array a using the loop counter
for (i = 1; i <= numbers; i++) {
a[i] = (long) i;
}
sum = 0;
for (i = 1; i <= numbers; i++) {
// do summation
sum = sum + a[i];
}
System.out.println("sum of numbers between 1 and " + numbers + " is " + sum);
}
}
# 1 楼答案
您的
a
数组永远不能包含数字5050,因为您将其设置为1。。100元。您的意思是,当总和达到50时,您想打印索引,在这种情况下请注意,没有必要为此设置两个单独的循环。为什么不将两者合并为一个循环: