首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阵列输出截断

阵列输出截断
EN

Stack Overflow用户
提问于 2015-07-26 16:36:00
回答 2查看 228关注 0票数 1

我编写了以下代码,它接受数组的输入并返回拉伸的数组。

例如

代码语言:javascript
复制
{18, 7, 9, 90}

应以下列方式退回:

代码语言:javascript
复制
{9, 9, 4, 3, 5, 4, 45, 45}

这就是我写的代码:

代码语言:javascript
复制
import java.util.Arrays;

public class Stretching
{
  public static void main(String[] args)
  {
    int[] list = {18, 7, 9, 90};
    int[] list2 = stretch(list);

    System.out.println(Arrays.toString(list));
    System.out.println(Arrays.toString(list2));
  }
  public static int[] stretch(int[] array)
  {
    int[] stretched = new int[2*array.length];
    for (int i = 0; i < array.length; i++)
    {
      if (array[i]%2 == 1)
      {
        stretched[i] = array[i]/2;
        stretched[i] = array[i]/2 + 1;
      }
      else
      {
        stretched[i] = array[i]/2;
        stretched[i] = array[i]/2;
      }
    }
    return stretched;
  }
}

不幸的是,输出如下:

代码语言:javascript
复制
[9, 3, 4, 45, 0, 0, 0, 0]

如何纠正此错误?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-26 16:42:03

您正在重用引用原始数组中位置的i索引。相反,由于您正在拉伸数组,目标索引应该是:

代码语言:javascript
复制
if (array[i]%2 == 1)
{
    stretched[2 * i] = array[i]/2 + 1;
    stretched[2 * i + 1] = array[i]/2;
}
else
{
    stretched[2 * i] = array[i]/2;
    stretched[2 * i + 1] = array[i]/2;
}
票数 3
EN

Stack Overflow用户

发布于 2015-07-26 16:44:46

这段代码有一个很大的错误。

代码语言:javascript
复制
  if (array[i]%2 == 1)
  {
    // Here array[i]/2+1 to index i
    stretched[i] = array[i]/2 + 1;
    // Here array[i]/2 to index i
    stretched[i] = array[i]/2;
  }
  else
  {
    // Here array[i]/2 to index i
    stretched[i] = array[i]/2;
    // Here array[i]/2 to index i
    stretched[i] = array[i]/2;
  }

在这里,您要在同一个索引上为拉伸的数组分配两个值,您真正想要的是将它们分配给连续的索引。

相反,您必须修改代码,如下所示

代码语言:javascript
复制
import java.util.Arrays;

class Stretching
{
  public static void main(String[] args)
  {
    int[] list = {18, 7, 9, 90};
    int[] list2 = stretch(list);

    System.out.println(Arrays.toString(list));
    System.out.println(Arrays.toString(list2));
  }
  public static int[] stretch(int[] array)
  {
    int[] stretched = new int[2*array.length];
    for (int i = 0; i < array.length; i++)
    {
      if (array[i]%2 == 1)
      {
        stretched[2 * i] = array[i]/2 + 1;
        stretched[2 * i + 1] = array[i]/2;
      }
      else
      {
        stretched[2 * i] = array[i]/2;
        stretched[2 * i + 1] = array[i]/2;
      }
    }
    return stretched;
  }
}

希望你能理解窃听器!!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31639383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档