【问题标题】:Constant stepped values in a new array新数组中的恒定步进值
【发布时间】:2020-11-24 11:22:53
【问题描述】:

我想基于恒定间隔的最小值和最大值创建一个新数组。例如,假设我的min = 5 和max = 50 和steps = 5,如何创建一个从min 开始到max 增量为steps 的新数组?

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

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

int myArr[] = {};

myArr[0] = min;

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

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

【问题讨论】:

  • 1.显然它不会工作,甚至不会编译 - 它不是 for 循环的正确语法。 2. 数组的大小是固定的,需要事先计算好元素的数量,并用正确的大小进行初始化。

标签: java arrays increment


【解决方案1】:

您没有指定数组的大小。你应该这样做:

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 <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

[P.S.]:如果有不清楚的地方,可以在评论区问我...

【讨论】:

  • 啊,有道理。我的坏,非常感谢你。感谢您的时间、帮助和解释,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2013-11-15
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多