1

有谁知道如何计算循环中的平均值。每次我计算我收到的平均值 0 或 1。我知道我需要使用平均值 = (sum) / (salary_annually); 但我无法让它工作。提前致谢。

 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;
    int 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 <= 2; year++)
         {

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

                          sum += salary_annually  ;
              if (min >= salary_annually) 
              { 
                     min = salary_annually;
              } 
             if (max <=salary_annually) 
             { 
               max = salary_annually;
              } 

            average = (sum) / (salary_annually); 


         }

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

   }
  }
4

4 回答 4

1

我猜这里的问题是您使用的是整数除法。由于 sum 和 Salary_annually 都是整数,除法的工作方式略有不同。没有余数,因为两个整数相除得到一个 int。

例如,1/2 不是您可能期望的 0.5,而是 0。在进行整数数学时,任何小数都会被丢弃。另一个例子 9/5 不是 1.8 而是 1。

如果您想要平均值,那么您可以将 sum 或 Salary_annually 声明为双精度数,并将平均值声明为双精度数。

于 2013-11-14T17:01:35.317 回答
0

平均值是通过average = sum / countwhere average 应该是 double 类型来计算的。

您确实声明了变量计数,但没有使用它。

import java.util.Scanner;

public class Calulate {

/**
 * @param args
 */
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 = 2;
    int salary_annually = 0;

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

        for (int year = 1; year <= count; year++) {

            System.out.println("Please Enter the Salary for Year: " + year);
            salary_annually = kb.nextInt();
            sum += salary_annually;

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

        }

        average = sum / count; 

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

}

}

于 2013-11-14T17:17:43.100 回答
0

改变

 average = (sum) / (salary_annually); 

 double average=0;// Declare it as `double` rather than `int`

 average = (sum) / 2.0; 
于 2013-11-14T17:01:23.870 回答
0
  1. 平均值计算如下:average = sum / count;
  2. 你需要增加你的count变量,否则你总是会得到和ArithmeticException / by zero
于 2013-11-14T17:04:11.633 回答