计算Loop Java中的平均值

时间:2013-11-17 22:29:02

标签: java

我刚刚发现,当我计算第二个用户的平均值时,我会得到不同的结果。例如,如果我为第一个用户10,10,10,20,20添加此号码。我得到14.0这是正确的。但是当我为第二个用户输入相同的号码时,我得到28.0?有任何想法吗?

import java.util.Scanner;

public class midterm 
{
  public static void main(String args[]) 
  {
    Scanner kb = new Scanner(System.in);

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    int sum = 0;
    double average=0;
    int count = 0;
    int salary_annually = 0;

    for(int employee =1; employee <= 2; employee++)
    {
      System.out.println("Employee: " + employee);

      for(int year=1; year <= 5; year++)
      {   
        System.out.println("Please Enter the Salary for Year: "  + year);
        salary_annually = kb.nextInt();

        sum += salary_annually  ;
        average = (sum) / 5.0; 

        if (min >= salary_annually) 
        { 
          min = salary_annually;
        } 

        if (max <=salary_annually) 
        { 
          max = salary_annually;
        } 
      }

      System.out.println("The average is " + average);
      System.out.println("The higher number  " + max);
      System.out.println("The the lowest number " + min);
    }
  }
}

2 个答案:

答案 0 :(得分:2)

sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
   .
   .
   .
}
average = (sum) / 5.0; // this after 2nd loop

在你的解决方案中,你在循环内平均计算5次!而你只是第五次获得优势!必须在循环之后。循环后average = (sum) / 5.0;

答案 1 :(得分:1)

您需要在循环结束时归零sum。实际上,现在它随着旧值保留在内存中而不断增加和增加,进入下一次迭代。