Determining Maximum and Mean of an User-Provided Array in Java

点点圈 提交于 2020-01-05 19:24:10

问题


I am new to coding so be easy on me. I am trying to determine the maximum and mean of an user-provided array using two separate classes (i.e. xyz and a separate xyztester class). I've have my coding but the maximum output is 0.0 and the mean output is one less than the length of the array. Here is my coding -

"xyz" class

public static double maximum(double[] array){
    double max = array[0];
    for (int j = 1; j < array.length; j++){
        if(array[j] > max){
            max = array[j];
        }
    }
    return max;
}

public static double mean(double[] array){
    double sum = 0;
    for (double k = 0; k < array.length; k++)
        sum = sum + array.length;

    double avg = sum / array.length;

    return avg;
}

"xyzTester" class

    double [] b;
    b = new double [quantArray];

    int j;
    for (j = 0; j > quantArray; j++){
        b[j] = in.nextDouble();
    }
    double n = xyz.maximum(b);

    double [] c;
    c = new double [quantArray];

    int k;
    for (k = 0; k > quantArray; k++){
        c[k] = in.nextDouble();
    }
    double o = xyz.mean(c);

Can someone detail what I am doing wrong?


回答1:


I see two problems:In the mean method

sum = sum + array.length;

Should probably be

sum = sum + array[k];

Secondly all floating point calculations should be between floating point operants. So better cast stuff like array length to double before dividing:

double avg = sum / (double)array.length;


来源:https://stackoverflow.com/questions/33186635/determining-maximum-and-mean-of-an-user-provided-array-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!