在计算列表奇数的平均值时遇到问题

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

我们的教授在一个文本文件中给了我们一个包含 982 个数字的列表,我们已经从文件中读取文本并打印出一些关于这些数字的信息。到目前为止,我的一切都是正确的(她给了我们正确的答案),除了奇数的总数。我不知道如何计算奇数的平均值,即 48201.56。

我一直得到结果 97354,这很奇怪,因为我使用的方法与我用来计算所有数字的平均值和偶数的平均值的方法相同。

        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);


           }


        }

我想知道为什么 "Total odd average" 的答案不是 48201.56。谢谢

您的 else 语句仅执行 c++; 操作。

像这样用括号括起来:

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

f += i; 在 else 语句之外执行,这意味着它在 while 的每个循环中被调用。如果你检查你的值,你应该发现 f 和 d 是相同的值。

如果按如下方式封装 else 语句,应该可以解决问题

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