【问题标题】:how to solve NaN error如何解决 NaN 错误
【发布时间】:2015-05-25 14:45:40
【问题描述】:

这是计算平均值的代码,当我运行我的项目时出现 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());
         }
        }

【问题讨论】:

  • 也许你在这里被0除average = attendence / no_of_matches ;
  • 如果你得到 NaN,这意味着你将浮动零除以零。

标签: java nan


【解决方案1】:

我认为问题可能出在这行代码上:

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;

【讨论】:

  • 非常感谢您的帮助。它的工作,但只计算一个平均值,这就是为什么打印 0.0
【解决方案2】:

我认为你可以在除法操作中使用之前修复 NAN 错误检查 if no_of_matches > 0

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_matches0 时,您的平均值将为 0,这意味着您没有匹配项。

希望这会有所帮助。

【讨论】:

  • 它以 0.0 的形式出现,现在我知道问题所在了。我想获得所有三个的平均值,但它只计算一个团队可能这就是为什么
猜你喜欢
  • 2017-10-10
  • 1970-01-01
  • 2020-11-22
  • 2017-03-02
  • 2020-09-08
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多