Mic*_*ael 20 java arrays loops
我需要创建一个包含100个数字(1-100)的数组,然后计算它将会是多少(1 + 2 + 3 + 4 + .. + 100 =总和).
我不想手动将这些数字输入到数组中,100个点需要一段时间并且代价更高.
我正在考虑使用变量++直到100,然后计算它的总和.不知道究竟会写得多么准确.但重要的是它在数组中,所以我也可以稍后说,"数组55多少",我可以很容易地看到它.
aio*_*obe 43
这是如何做:
// 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);
Run Code Online (Sandbox Code Playgroud)
Bal*_*a R 10
如果您只想计算1,2,3 ... n的总和,那么您可以使用:
int sum = (n * (n + 1)) / 2;
Run Code Online (Sandbox Code Playgroud)
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
286034 次 |
| 最近记录: |