user9701731
user9701731

Reputation:

logic error when trying to find the average of an array

i made a method that calculates the average of an array. im getting weird numbers though. when i constructed an array consisting of 1, 9, 5, 0, 7 it said the average was 3, it should be 5 but i cant see whats wrong with my method.

public static int Average(Array_one A) {
        int ave = 0;
        int[] a = A.values;
        for (int i = 0; i < A.size; i++) {
            double tmp = a[i] * 1.0;
            ave += (tmp / A.size);
        }
        return ave;

Upvotes: 0

Views: 117

Answers (5)

Anthony Marino
Anthony Marino

Reputation: 97

You just need to pull the division outside of the for loop so you're adding all of the numbers in the array, then dividing by the total

public static int Average(Array_one A) {
    int ave = 0;
    int[] a = A.values;
    for (int i = 0; i < A.size; i++) {
        double tmp = a[i] * 1.0;
        ave += tmp;
    }
    ave = ave/A.size;
    return ave;

Upvotes: 1

Josh
Josh

Reputation: 326

The problem seems to be in your mathematics:

You are adding 1/6 + 9/6 + 5/6 + 0/6 + 7/6.

Which comes out to 22/6. Except that you declared ave as an int, so your progam is throwing away remainders and causing all sorts of mathematical issues.

You should declare the average as a double first. Then, you should add up all of the numbers into tmp without dividing.

After that, divide tmp by ave and you should get the correct result.

Upvotes: 0

Abhijeet Kale
Abhijeet Kale

Reputation: 389

The avg is not 5 it comes 4.4 by using following code.

import java.io.*;
public class Test {

   public static void main(String args[]) {

        double ave = 0;
        int[] a = {1, 9, 5, 0, 7};
        double tmp = 0;

        for (int i = 0; i < a.length; i++) {
            tmp += a[i];
        }
        ave += (tmp / a.length);
        System.out.println(ave);
   }
}

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

You have to find a sum first and then divide it by elements amount. To not loose a precision.

public static double avg(int[] arr) {
    int sum = 0;

    for (int val : arr)
        sum += val;

    return (double)sum / arr.length;
}

Upvotes: 1

Michu93
Michu93

Reputation: 5721

Why don't you use streams?

public static void main(String[] args) {

        int[] arr = {1,9,5,0,7};

        double average = Arrays.stream(arr)
                .average()
                .orElse(-1);
        System.out.println(String.format("Average: %s", average));

    }

Upvotes: -2

Related Questions