Java的:磁盘阵列和循环 [英] Java: Array with loop

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

问题描述

我需要用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);


IDEONE.com演示

这篇关于Java的:磁盘阵列和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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