这是一个代码,用于获取用户估算的成绩,找到他们的平均值,偏差,并以表格样式显示此信息。我的程序接受用户输入并很好地显示信息,但它不会正确计算平均值和偏差。运行时,它显示平均值为 0。我的做法与我的老师教我们的原因相同,但我找不到我的错误。
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
average(grades, mean);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades, double mean)
{
double total = 0;
for (double i : grades)
{
total += i;
}
if (grades.length>0)
{
mean = total/grades.length;
}
return mean;
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
这是任何好奇的人的编辑代码。
导入 java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
mean = average(grades);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades)
{
double total = 0;
for (double i : grades)
{
total += i;
}
return total/(grades.length);
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}