新数组中的恒定步进值
Constant stepped values in a new array
我想根据恒定间隔内的最小值和最大值创建一个新数组。例如,假设我的 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;
}
任何帮助或建议将不胜感激。
您没有指定数组的大小。你应该这样做:
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.]:有什么不懂的可以在评论区问我...
我想根据恒定间隔内的最小值和最大值创建一个新数组。例如,假设我的 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;
}
任何帮助或建议将不胜感激。
您没有指定数组的大小。你应该这样做:
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.]:有什么不懂的可以在评论区问我...