简体   繁体   中英

Having issues calculating the average of the odd numbers of a list

Our professor gave us a list of 982 numbers in a text file and we have read text from the file and print out some info about the numbers. I have everything correct so far, (she gave us the correct answers), except the total of the odd numbers. I can't figure out how to get the average of the odd numbers which is 48201.56.

I keep getting the result 97354, which is weird because I'm following the same method I used to find the average of all the numbers and the average of the even numbers.

        import java.io.*;
        import java.util.*;
        public class Homework1sem2
        {
           public static void main(String args[]) throws IOException
           {
              System.out.println("Student name: Ethan Creveling "
              + "\nEmail: ec904066@wcupa.edu");
              double f = 0;
              double e = 0;
              double d = 0;
              int c = 0;
              int b = 0;
              int a = 0;
              File myFile = new File("numbers.txt");
              Scanner inputFile = new Scanner(myFile);
              while (inputFile.hasNext())
              {
                 int i = inputFile.nextInt();
                 a++;
                 d += i;

                 if(i%2 == 0)
                 {
                    b++;
                    e += i;
                 }
                 else
                    c++;
                    f += i;
              }
              System.out.println("Total number: " + a);
              System.out.println("Total even number: " + b);
              System.out.println("Total odd number: " + c);
              System.out.println("Total average: " + d/a);
              System.out.println("Total even average: " +e/b);
              System.out.println("Total odd average: " + f/c);


           }


        }

I would like to know why the answer for "Total odd average" isn't 48201.56. Thanks

Your else statement is only performing the c++; operation.

Wrap it in brackets like this:

else {
  c++;
  f += i;
}

f += i; is being performed outside of the else statement which means that it is being called on every loop of the while. If you check your values, you should find that both f and d are the same value.

If you encapsulate your else statement as follows, this should fix the problem

else {
  c++;
  f += 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