2016-05-23 48 views
-3

我正在尝试编写一个脚本来计算班级的平均GPA,并显示学生取得的最低和最高成绩。 我正在尝试如何获得12个数字的平均值。我知道我需要添加所有数字并将它们分开12.有人能给我一些关于如何做到这一点的提示。 Thansk!Java:用12个学生的intArr计算平均GPA

+0

请仔细阅读下面的内容:http://meta.stackexchange.com/questions/10811/how-do-i-ask -and-answer-homework-questions – SiKing

回答

1

假设12名学生有数组中的成绩将intArr

public int calculateAverage(){ 

int intArr = {1,2,3,4,5,6,7,8,9,10,11,12}; 
//Total number of students grades in the array 
int totalStudents = intArr.length; 

//Variable to keep the sum 
int sum = 0; 
for (int i = 0; i < totalStudents; i++){ 
    sum = sum + intArr[i];//Add all the grades together 
} 

int average = sum/totalStudents; 
return average; 
} 
+0

这是行不通的。 int必须声明为数组,否则会显示错误。 – Zoe

1

如果您使用的是Java 8有良好的设施统计:

IntSummaryStatistics stats = Arrays.stream(grades).summaryStatistics(); 

然后你可以使用stats.getMinstats.getAverage

另一方面,如果这是一项家庭作业,那么你可能应该编写自己的代码来做到这一点,而不是使用t他是Java库。

0

@SiKing说什么,你试过什么代码?告诉我们你编码的东西!

@ nitinkc的代码在正确的轨道上,尽管OO标准并不完全正确。

这是我的。这只是一个功能。你必须自己实施你的亚军,假设你只有一个主要亚军类...

// initialise and pass in your array into your function 
public static double calculateAverage(int[] array) { 

    // double because averages are more than likely to have decimals 
    double gradesTotal = 0; 

    // loop through each item in your array to get the sum 
    for(int i = 0; i < array.length; i++) { 
     gradesTotal = gradesTotal + array[i]; 
    } 

    // return the sum divided by number of grades 
    return gradesTotal/array.length; 
}