英文:
Java for loop returning the same number multiple times
问题
我有一个 for 循环,试图通过添加前一个值的两倍的新数组元素来扩展数组。例如:
起始于:array = {1}
结束于:array = {1, 2, 4, 8, 16, 等等}
目前我的 for 循环输出的数组是这样的:array = {1, 2, 2, 4, 4, 8, 8, 16}
由于某种原因,它会把相同的数字重复添加两次。
只需将变量 "input" 视为 21:
for (int i = 0; (nums[i] * 2) < input; i++)
{
if (i == 0)
{
nums = IncreaseArrayInt(nums, nums[(i)] * 2);
}
else
{
nums = IncreaseArrayInt(nums, nums[(i - 1)] * 2);
}
}
以下是我用来扩展数组的函数:
static int[] IncreaseArrayInt(int[] oldArray, int insertValue)
{
int[] newArray = new int[oldArray.length + 1];
for(int i = 0; i < oldArray.length; i++)
{
newArray[i] = oldArray[i];
}
newArray[oldArray.length] = insertValue;
return (newArray);
}
它与预期几乎非常接近,希望有人能够看出我所忽略的问题。
英文:
I have a for loop that is trying to extend an array by adding new array element that is double the previous value.
e.g.
starting at : array = {1}
ending at : array = {1, 2, 4, 8, 16, etc}
Currently my for loop spits out an array like this : array = {1, 2, 2, 4, 4, 8, 8, 16}
It puts the same number in twice for some reason.
Just see the variable "input" as 21
for (int i = 0; (nums[i] * 2) < input; i++)
{
if (i == 0)
{
nums = IncreaseArrayInt(nums, nums[(i)] * 2);
}
else
{
nums = IncreaseArrayInt(nums, nums[(i - 1)] * 2);
}
}
Heres the function i used to extend the array:
static int[] IncreaseArrayInt(int[] oldArray, int insertValue)
{
int[] newArray = new int[oldArray.length + 1];
for(int i = 0; i < oldArray.length; i++)
{
newArray[i] = oldArray[i];
}
newArray[oldArray.length] = insertValue;
return (newArray);
}
Its very close to working as intended and hoping some can see the issue im missing
答案1
得分: 1
变更:
nums = IncreaseArrayInt(nums, nums[(i)] * 2);
英文:
Change:
nums = IncreaseArrayInt(nums, nums[(i - 1)] * 2);
to:
nums = IncreaseArrayInt(nums, nums[(i)] * 2);
答案2
得分: 0
问题在于for循环中的前两次迭代都使insertValue乘以2。你应该摒弃if else语句,而是对所有可能的i值使用nums = IncreaseArrayInt(nums, nums[(i)] * 2);
。
英文:
The problem is that the first two passes in the for loop both make insertValue 1 * 2. you should get rid of the if else statement and just use nums = IncreaseArrayInt(nums, nums[(i)] * 2);
for all of the possible values of i.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论