gpt4 book ai didi

java - 制作一个打印给定数字倍数的数组

转载 作者:行者123 更新时间:2023-11-30 08:39:43 24 4
gpt4 key购买 nike

我需要帮助制作一个打印出给定数字倍数的数组。输出如下所示:

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

关于java - 制作一个打印给定数字倍数的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com