[英]how to solve NaN error
這是計算平均值的代碼,當我運行我的項目時,我收到NaN錯誤
public static double calculateAverage(){
double attendence = 0;
int no_of_matches = 0;
double average =0;
for (Team t: ApplicationModel.getTeamList()){
for(Match m : ApplicationModel.getMatchList()){
if(m.getTeamname().equals(t.getName())){
attendence =+ (m.getAttendence());
no_of_matches ++;
}
}
average = attendence / no_of_matches ;
}
return average;
}
這是調用計算平均方法的代碼
String[] columnNames = {"Name","Coaches","League","Division","Fulltime","Number of Coaches","Average Attendence"};
if (ApplicationModel.getTeamList()!=null){
int arrayIndex=0;
for (Team c :ApplicationModel.getTeamList()){
String[] currentRow = new String[7];
currentRow[0] = c.getNameAsString();
currentRow[1] = c.getCoachesAsString();
currentRow[2] = c.getLeague();
currentRow[3] = c.getDivision();
currentRow[4] = c.getFulltime();
currentRow[5] = Integer.toString(c.getCoaches().length);
currentRow[6] = Double.toString(c.calculateAverage());
rowInfo[arrayIndex]=currentRow;
arrayIndex++;
teamDisplay.append(c.toString());
}
}
我認為問題可能是這行代碼:
attendence =+ (m.getAttendence());
您可以將總變量分配給值,而不是將值添加到總變量中。 另一個問題是你沒有處理no_of_matches
(在命名約定方面是一個可怕的變量名)為0
,即沒有匹配。 最后, average = attendence / no_of_matches
總是重新分配average
,從而丟棄前一個團隊的任何結果。
代碼建議:
double attendence = 0;
int matches = 0;
for (Team t: ApplicationModel.getTeamList())
{
for(Match m : ApplicationModel.getMatchList())
{
if(m.getTeamname().equals(t.getName()))
{
attendence += (m.getAttendence());
matches++;
}
}
}
return matches > 0 ? attendence / matches : 0D;
我認為如果在分割操作中使用no_of_matches > 0
之前你可以修復NAN錯誤檢查。
public static double calculateAverage(){
double attendence = 0;
int no_of_matches = 0;
double average = 0;
for (Team t: ApplicationModel.getTeamList()) {
for (Match m: ApplicationModel.getMatchList()) {
if (m.getTeamname().equals(t.getName())) {
attendence =+ (m.getAttendence());
no_of_matches ++;
}
}
if (no_of_matches > 0)
average = attendence / no_of_matches ;
}
return average;
}
附加說明,當您添加此檢查並且no_of_matches
為0
您的平均值將為0,這意味着您沒有匹配項。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.