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

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

Constant stepped values in a new array

问题

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

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

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

int myArr[] = {};

myArr[0] = min;

for(int i = min, i <= max; i++){
   myArr[i] = min + step;
}

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

英文:

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:

int myArr[] = {};

myArr[0] = min;

for(int i = min, i <= max; i++){
   myArr[i] = min + step;
}

Any help or advice will be highly appreciated.

答案1

得分: 0

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

public class SOTest {
    public static void main(String[] args) {
        int min = 5; // 使用您喜欢的值
        int max = 50; // 使用您喜欢的值
        int step = 5; // 使用您喜欢的值

        // 现在,确定数组大小
        // 这是一个简单的计算,确定了如果我们按步骤从min到max跳跃,将有多少个元素
        int size = (max + step - min) / step;

        int[] myArr = new int[size]; // 在创建数组时,您需要指定数组的大小,即数组可以容纳多少个元素

        int val = min;
        for(int i = 0; i < size; i++){
           myArr[i] = val;
           val = val + step;
        }

        for(int i = 0; i < size; i++) {
           System.out.print(myArr[i] + " ");
        }

        System.out.println();
    }
}

输出结果是:

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

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

public class SOTest {
    public static void main(String[] args) {
        int min = 5; // use whatever you prefer
        int max = 50; // use whatever you prefer
        int step = 5; // use whatever you prefer

        // now, determine size
        // its a simple calculation, that
        // determines how many elements would there be from min to
        // max if we jump by step
        int size = (max + step - min) / step;

        int[] myArr = new int[size]; // while creating array you need to specify
        // the size of the array, i.e. how many elements the array could hold

        int val = min;
        for(int i = 0; i &lt;size; i++){
           myArr[i] = val;
           val = val + step;
        }

        for(int i=0; i&lt;size; i++) {
           System.out.print(myArr[i] + &quot; &quot;);
        }

        System.out.println();
    }
}

And the output is:

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:

确定