沒有人知道如何計算循環中的平均值。每次我計算平均收到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);
}
}
}
AFAIK平均值由總和/計數來計算。 – Pietu1998
在計算之前,'int'值應該是'double'(或者提升爲'double')。 –
平均值應計算在循環內部 - 'average =(sum)/ 2;' – Akshay