Java for循环多次返回相同的数字

huangapple go评论70阅读模式
英文:

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) &lt; 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 &lt; 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.

huangapple
  • 本文由 发表于 2020年10月7日 06:13:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64234528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定