我需要帮助制作一个打印出给定数字的倍数的数组。输出如下:
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的数组中。我只是不确定如何创建一个给我正确输出的循环。 非常感谢你!
答案 0 :(得分:2)
在你的乘法方法中,你并没有成倍增加。试试这个:
//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
进行统计答案 1 :(得分:0)
您的问题是您继续计算相同的结果。您将“n”传递给您的方法,并将n + 10的结果存储在数组的每个索引(i)中。
你想要的是这样的东西(仅使用时间5例子):
int[] temp = new int[n];
for(int i = 1; i <= n; i++)
{
temp[i-1] = i * 5;
}