代码之家  ›  专栏  ›  技术社区  ›  Barin Mangal

使用BubbleSort方法求平均值

  •  0
  • Barin Mangal  · 技术社区  · 7 年前

    我是一名IT专业的学生,我真的需要完成这段代码,我几乎完成了,它使用冒泡排序对数字进行排序,但问题是,我们必须在最后找到平均值,我不知道怎么做。有人能帮我吗? 我的代码看起来是这样的,在这里它也起作用之前,我只需要将其余部分添加到其中:

    public static void main(String[] args) {
        int num, i, j;
        double temp;
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
    
        System.out.println("Enter the amount of Numbers you want to sort:");
        num = input.nextInt();
    
        double array[] = new double[num];
    
        System.out.println("Enter " + num + " Number: ");
    
        for (i = 0; i < num; i++)
            array[i] = input.nextDouble();
    
        for (i = 0; i < (num - 1); i++) {
            for (j = 0; j < num - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    
        System.out.println("Sorted list:");
    
        for (i = 0; i < num; i++)
            System.out.println(array[i]);
    }
    

    }

    谢谢:)

    2 回复  |  直到 7 年前
        1
  •  0
  •   Mathews Sunny Vivek Mehta    7 年前

    你只需要编辑一下。只需在程序中添加一个变量平均值,如果需要整数平均值,则添加int variable,如果需要精确结果,则添加float(如下代码所示)。将所有元素求和为变量和(整数元素),然后将其除以元素总数(基础数学!!!)。就这样,打印出来,你就完成了。

    您的程序应该如下所示:

    public static void main(String[] args) {
    int num, i, j, sum=0;
    float avg=0;
    double temp;
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    
    System.out.println("Enter the amount of Numbers you want to sort:");
    num = input.nextInt();
    
    double array[] = new double[num];
    
    System.out.println("Enter " + num + " Number: ");
    
    for (i = 0; i < num; i++)
        array[i] = input.nextDouble();
    
    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    
    System.out.println("Sorted list:");
    
    for (i = 0; i < num; i++)
        System.out.println(array[i]);
    
    for (i = 0; i < num; i++)
     sum = sum+array[i];
    avg=sum/num;
    System.out.println("Average : "+avg);
     }
    }
    
        2
  •  0
  •   Thomas    7 年前
     int avg = 0;   
     for (i = 0; i < num; i++) {
         avg = avg + array[i];
     }
     avg = avg / array.length();