gpt4 book ai didi

Java:带循环的数组

转载 作者:IT老高 更新时间:2023-10-28 21:03:47 24 4
gpt4 key购买 nike

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

我不想手动将这些数字输入到数组中,100 个点会花费一些时间并且会花费更多代码。

我正在考虑使用变量++ 直到 100,然后计算它们的总和。不知 Prop 体怎么写。但重要的是它在数组中,所以我以后也可以说,“数组 55 是多少”,我可以很容易地看到它。

最佳答案

方法如下:

// 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:带循环的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7687310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com