有谁知道如何计算循环中的平均值。每次我计算平均值时我都会收到0或1.我知道我需要使用average =(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);
}
}
}
答案 0 :(得分:1)
我猜这里的问题是你使用的是整数除法。由于总和和一年两次的整数划分工作略有不同。没有余数,因为除以两个整数给出一个int。
例如,1/2不是.5,正如您所料,但它是0.当进行整数运算时,任何小数都会被丢弃。另一个例子是9/5不是1.8,而是1.
如果你想要平均值那么你可以将sum或salary_annually声明为double,并将平均值声明为double。
答案 1 :(得分:0)
更改
average = (sum) / (salary_annually);
要
double average=0;// Declare it as `double` rather than `int`
average = (sum) / 2.0;
答案 2 :(得分:0)
average = sum / count;
count
变量,否则您将始终获得ArithmeticException / by zero
答案 3 :(得分:0)
平均值由average = sum / count
计算,其中平均值应为double类型。
您确实声明了变量count,但没有使用它。
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);
}
}
}