仅从绝对值将数组转换为数组

时间:2015-12-11 09:23:20

标签: java arrays

我无法将负数组元素转换为绝对数组。到目前为止,我已经使数组包含负数和正数,但我必须将它们转换为绝对数,以便计算数组平方根。有什么建议吗?

 public static void main(String[] args) {
    int min = -100;
    int max = 100;

    int[] array = new int[201];
    for (int i = 0; i < array.length; i++) {

        array[i] = min + (int) (Math.random() * ((max - min) + 1));

        //System.out.println(array[i]);
    }

    int[] array2 = new int[array.length];
    for (int j = 2; j < array.length; j += 3) {
       array2[j] = array[j];
       //System.out.println(array[j]);



        double[] result = new double[array2.length];
        for (int i = 0; i < array2.length / 3; i++) {

            array2[i] = Math.abs(i);
            result[j] = Math.sqrt(array[j]); 
            System.out.println(array[i]);
        }

3 个答案:

答案 0 :(得分:1)

你的第三行是错误的,你需要:

result[j] = Math.sqrt(array2[j]);

答案 1 :(得分:1)

您在i(索引)上调用的array2[i]不在数组元素上。此外,您将abs的结果存储到Math.sqrt(),然后在不同的数组和元素(array[j])上调用protected void Add<T>(T source, MyEntities context, bool isNew, EntityState state) where T : class { if (isNew) { context.CreateObjectSet<T>().AddObject(source); } else { if (state == EntityState.Detached) { context.CreateObjectSet<T>().Attach(source); context.ObjectStateManager.ChangeObjectState(source, EntityState.Modified); } } } 。还要检查你的for循环索引是否以你想要的方式迭代字段(对我来说for循环语句看起来有些奇怪)。

答案 2 :(得分:0)

你必须清楚地描述你的意图, 你不清楚你想要数组的每个第三个元素而不是每一个元素。

然而,有多种方法可以实现结果。

  1. 您可以创建List来存储每个第三个元素的平方根

    List<Double> result1 = new ArrayList<>();
    for (int j = 2; j < array.length; j += 3) {
        result1.add(Math.sqrt(Math.abs(array[j])));
    }
    
  2. 如果您想使用数组,请按照

    进行操作
    double[] result2 = new double[array.length / 3];
    for (int j = 2; j < array.length; j += 3) {
        result2[j / 3] = Math.sqrt(Math.abs(array[j]));
    }
    
  3. 在这两个示例中,我们调用Math.abs来获取绝对值,并Math.sqrt来获得平方根。

    这是完整的代码

    public static void main(String args[])
    {
        int min = -100;
        int max = 100;
    
        int[] array = new int[201];
        for (int i = 0; i < array.length; i++) {
            array[i] = min + (int) (Math.random() * ((max - min) + 1));
        }
    
        List<Double> result1 = new ArrayList<>();
        for (int j = 2; j < array.length; j += 3) {
            result1.add(Math.sqrt(Math.abs(array[j])));
        }
    
        double[] result2 = new double[array.length / 3];
        for (int j = 2; j < array.length; j += 3) {
            result2[j / 3] = Math.sqrt(Math.abs(array[j]));
        }
    
        System.out.println(result1);
        System.out.println(Arrays.toString(result2));
    }