2013-11-14 78 views
1

沒有人知道如何計算循環中的平均值。每次我計算平均收到0或1.我知道我需要使用average =(sum)/(salary_annually);但我無法讓它工作。提前致謝。計算嵌套循環中的平均數Java

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

    } 
    } 
+2

AFAIK平均值由總和/計數來計算。 – Pietu1998

+1

在計算之前,'int'值應該是'double'(或者提升爲'double')。 –

+0

平均值應計算在循環內部 - 'average =(sum)/ 2;' – Akshay

回答

1

我猜這裏的問題是,你正在使用整數除法。由於總額和薪金每年都是整數劃分工作略有不同。沒有餘數,因爲除以兩個整數給出一個整數。

例如,1/2不是.5,正如您所期望的那樣,但是它是0.在進行整數運算時,將刪除任何小數。另外一個例子9/5不是1.8而是1.

如果你想得到平均值,那麼你可以將sum或salary_annually聲明爲double,並將平均值聲明爲double。

0

變化

average = (sum)/(salary_annually); 

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

average = (sum)/2.0; 
0
  1. 平均的計算方法是:average = sum/count;
  2. 你需要增加你的count變量,否則你總是會得到和ArithmeticException/by zero
0

平均值由average = sum/count計算,其中平均應該是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); 
    } 

} 

}