简体   繁体   中英

Method subtracting elements of array from average of array numbers

I have an array of type double that is filled from values that the user enters, these values are lap times for a swimming race. It stores the times in lapArray and I have a few methods but one calculates the average of all the numbers in lapArray . However, I have another method getDeviationsArray that is supposed to find out if the lap times are below the average or above the average and fill an array called devArray with these results.

Basically just subtracting each lap time from the average, however if the lap time is higher than the average I get a result of 0 . This could be my rounding but I want to get a negative result which would be a slower time.

This is my expected output:

在此处输入图像描述

I have the first four rows which my other methods getFastest , getSlowest , getAverage , and get raceTime have done already. I just need to properly subtract the laptimes from the average and then also find a way that If the laptime was more than the average that it should have a ( + ) sign and less than average has a ( - ) sign.

Code:

public static double[] getDeviationsArray(Double[] inputArray) {
    double[] devArray = new double[inputArray.length];
    double diff = 0;
    for (int i = 0; i < inputArray.length - 1; ++i) {
        if (inputArray[i] < getAverageSplit(inputArray)) {
            diff = Math.abs(inputArray[i] - getAverageSplit(inputArray));
            devArray[i] = diff;
        } else {
            diff = Math.abs(getAverageSplit(inputArray) - inputArray[i]);
            devArray[i] = diff;
        }
    }
    return devArray;
}
System.out.println("Here are the split-times and deviations for each lap/length:\n");
double[] devArray1 = getDeviationsArray(lapArray);
DecimalFormat df = new DecimalFormat("#.##");
int index1 = 1;
for (int i = 0; i < lapArray.length; i++) {
    System.out.println("Lap or length #" + index1 + ": " + lapArray[i] + " seconds ("
            + Double.valueOf(df.format(devArray1[i])) + ")");
    index1++;
}

It feels like you are overcomplicating this. You should leave the negative diffs negative rather than using abs and then format with '+' sign:

double[] devArray = new double[inputArray.length];
double average = getAverageSplit(inputArray));
for (int i = 0; i < inputArray.length; ++i) {
    devArray[i] = inputArray[i] - average;
}

Also be aware that this can be done with a stream operation which might be a bit more straightforward:

double[] devArray = Arrays.stream(inputArray).map(t -> t - average).toArray();

Then use the following code to format with a sign symbol and 2 decimals:

String.format("%+.2f", devArray[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM