英文:
Constant stepped values in a new array
问题
我想创建一个新数组,基于常量间隔内的最小值和最大值。例如,假设我的min = 5
和max = 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 <size; i++){
myArr[i] = val;
val = val + step;
}
for(int i=0; i<size; i++) {
System.out.print(myArr[i] + " ");
}
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...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论