Java的:磁盘阵列和循环 [英] Java: Array with loop
问题描述
我需要用100个号码(1-100)创建一个数组,然后计算多少这一切将是(1 + 2 + 3 + 4 .. + 100 =总和)。
I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4..+100=sum).
我不希望这些数字进入阵列手动,100点会需要一段时间,花费更多的code。
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
我想是这样使用可变++到100,然后计算出这一切的总和。不知道它究竟是如何将被写入。
但它的重要,它在阵列,所以我也可以说后,多少是阵列55,我可以很容易看到它。
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written. But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
感谢很多提前,
迈克尔。
Thanks a lot in advance, Michael.
推荐答案
下面的方式:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
这篇关于Java的:磁盘阵列和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!