-1

Gives wrong answer only and I can't find the reason why? This is only part of the code but the rest was copy pasted so it does the same thing. I have tried to tweak it and find a solution online but everything seems to be in order. Maybe the counter is incorrect and can't deal with the negative numbers? The answer is always 107.19999999.

public class draft3 {
    public static void main (String []args) {
    
    /* Create arrays for each company*/ 
    int NL5755[] = new int[] {60, 70, -10, -12, 10};
//Assign a value of 0 to total
    double sum = 0;
    double average1=0;
{
        /*Use a counter. For i smaller than the*/ 
        /*value of the length of the array, add them to sum*/
    for(int i=0; i<NL5755.length; i++)
    {
        sum = sum + NL5755[i];

    average1 += sum / NL5755.length;
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Red Ink
  • 19
  • 4
  • The average calculation should be *after* the loop that calculates the sum. – Joachim Sauer Nov 17 '20 at 16:36
  • I'm also just going to mention that this is the _exact_ use case for [`LongAccumulator::avg`](https://spark.apache.org/docs/latest/api/java/org/apache/spark/util/LongAccumulator.html#avg--) which would better be able to handle overflows, etc. which might come up depending on the size of the `int`s, or the number of elements involved. – BeUndead Nov 17 '20 at 16:43

3 Answers3

1

You didn't use brackets properly.

public class draft3 {
    public static void main (String []args) {
    
    int NL5755[] = new int[] {60, 70, -10, -12, 10};
    double sum = 0;
    double average1=0;
    
    for(int i=0; i<NL5755.length; i++){
      sum = sum + NL5755[i];
    }
    average1 += sum / NL5755.length;
  }
}
avisionx
  • 220
  • 1
  • 8
0

to calculate the average of an array of numbers:

  1. firstly you need to sum all the numbers
  2. divide the sum of all numbers by the count of numbers.

note: the problem with your code is that you did the average on each iteration of loop:

int NL5755[] = new int[] { 60, 70, -10, -12, 10 };
double sum = 0;
double average1 = 0;
for (int i = 0; i < NL5755.length; i++) {
    sum = sum + NL5755[i];
}
average1 = sum / NL5755.length;
System.out.println(average1);
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
0

Other people have mentioned the fact that you should move the average calculation outside of the for loop, which is true if you want to calculate the average after you finish with the sum. However, if you want to calculate the average inside the for loop, it's possible to do with an online algorithm (i.e. "as you go"). In that case, you'd replace your current average1 line with:

average1 += (NL5755[i] - average1) / (i + 1);