Java:带循环的数组 [英] Java: Array with loop

查看:21
本文介绍了Java:带循环的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个包含 100 个数字 (1-100) 的数组,然后计算它们的总和 (1+2+3+4+..+100 = sum).

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 个点会花费一些时间并且花费更多的代码.

I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.

我在想一些事情,比如使用 variable++ 直到 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.

推荐答案

方法如下:

// 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆