常数步长值在一个新数组中。

huangapple go评论129阅读模式
英文:

Constant stepped values in a new array

问题

我想创建一个新数组,基于常量间隔内的最小值和最大值。例如,假设我的min = 5max = 50以及steps = 5,我该如何创建一个从min开始,以steps增量前进到max的新数组?

这样我的数组可以看起来像这样:[5, 10, 15, 20...., 50]

我尝试了以下方法,但似乎不起作用:

  1. int myArr[] = {};
  2. myArr[0] = min;
  3. for(int i = min, i <= max; i++){
  4. myArr[i] = min + step;
  5. }

任何帮助或建议都将不胜感激。

英文:

I would like to create a new array, based on minimum and maximum values in constant intervals. For example, suppose my min = 5 and max = 50 and steps = 5, how can I create a new array that starts at min and goes to max increments of steps?

So that my array can look like this : [5, 10, 15, 20...., 50]

I tried the following but it does not seem to work:

  1. int myArr[] = {};
  2. myArr[0] = min;
  3. for(int i = min, i <= max; i++){
  4. myArr[i] = min + step;
  5. }

Any help or advice will be highly appreciated.

答案1

得分: 0

你没有指定数组的大小。应该按照以下方式操作:

  1. public class SOTest {
  2. public static void main(String[] args) {
  3. int min = 5; // 使用您喜欢的值
  4. int max = 50; // 使用您喜欢的值
  5. int step = 5; // 使用您喜欢的值
  6. // 现在,确定数组大小
  7. // 这是一个简单的计算,确定了如果我们按步骤从min到max跳跃,将有多少个元素
  8. int size = (max + step - min) / step;
  9. int[] myArr = new int[size]; // 在创建数组时,您需要指定数组的大小,即数组可以容纳多少个元素
  10. int val = min;
  11. for(int i = 0; i < size; i++){
  12. myArr[i] = val;
  13. val = val + step;
  14. }
  15. for(int i = 0; i < size; i++) {
  16. System.out.print(myArr[i] + " ");
  17. }
  18. System.out.println();
  19. }
  20. }

输出结果是:

  1. 5 10 15 20 25 30 35 40 45 50
英文:

You didn't specify the size of the array. You should do as follows:

  1. public class SOTest {
  2. public static void main(String[] args) {
  3. int min = 5; // use whatever you prefer
  4. int max = 50; // use whatever you prefer
  5. int step = 5; // use whatever you prefer
  6. // now, determine size
  7. // its a simple calculation, that
  8. // determines how many elements would there be from min to
  9. // max if we jump by step
  10. int size = (max + step - min) / step;
  11. int[] myArr = new int[size]; // while creating array you need to specify
  12. // the size of the array, i.e. how many elements the array could hold
  13. int val = min;
  14. for(int i = 0; i &lt;size; i++){
  15. myArr[i] = val;
  16. val = val + step;
  17. }
  18. for(int i=0; i&lt;size; i++) {
  19. System.out.print(myArr[i] + &quot; &quot;);
  20. }
  21. System.out.println();
  22. }
  23. }

And the output is:

  1. 5 10 15 20 25 30 35 40 45 50

P.S.: If anything is unclear, just ask me in the comment section...

huangapple
  • 本文由 发表于 2020年8月4日 19:08:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63245601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定