我需要帮助制作一个可以打印出给定数字的倍数的数组。输出如下:
Enter a positive integer: 8
Test array: 1 1 2 3 5 8 13
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
这是我到目前为止的代码:
//Creates an array that counts up to the user input
public static int[] countUp(int n){
int [] temp = new int[n];
for(int i=0; i<n; i++){
temp[i] = i+1;
}
return temp;
}
//Creates an array that counts down to the user input
public static int[] countDown(int n){
int [] temp = new int[n];
for(int i=0; i<temp.length; i++){
temp[i] = n--;
}
return temp;
}
//Creates an array that gets n amount of multiples of 5
public static int[] getMultiplesOfFive(int n){
int [] temp = new int[n];
for(int i=0; i<temp.length; i++){
temp[i] = n+5;
}
return temp;
}
//Creates an array that gets n amount of multiples of 10
public static int[] getMultiplesOfTen(int n){
int [] temp = new int[n];
for(int i=0; i<temp.length; i++){
temp[i] = n+10;
}
return temp;
}
}
但是我的输出看起来像这样:
Enter a positive integer: 8
Test array: 1 1 2 3 5 8 13
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 13 13 13 13 13 13 13 13
The first 8 multiples of 10: 18 18 18 18 18 18 18 18
显然问题出在最后两个名为getMultiplesofFive和getMultiplesofTen的数组中。我只是不确定如何创建一个循环给我正确的输出。太感谢了!
在您的乘法方法中,您没有进行乘法。试试这个:
//Creates an array that gets n amount of multiples of 5
public static int[] getMultiplesOfFive(int n){
int [] temp = new int[n];
for(int i=0; i<temp.length; i++){
temp[i] = (i+1)*10;
}
return temp;
}
//Creates an array that gets n amount of multiples of 10
public static int[] getMultiplesOfTen(int n){
int [] temp = new int[n];
for(int i=0; i<temp.length; i++){
temp[i] = (i+1)*10;
}
return temp;
}
加(i + 1),因为索引将从0开始,并且您要使用n * 1进行统计
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句