首页 > 解决方案 > 难以准确找到平均时间

问题描述

我正在为我的大学作业做一个项目,我正在努力准确地找到我的程序的平均歌曲持续时间。

我输入 3:33 的持续时间 3 次并从 arrayList 获取输入,它应该返回 3:33 的结果。但是,我得到的结果是 3:19。

我不太确定我哪里出错了,我已经尝试在这里和那里改变一些东西,但仍然得到相同的结果。

public void display()
{
    String durationTemp = "";
    String durationStr = "";
    double durationDbl = 0;
    double durationTotal = 0;
    double durationAvg = 0;

    double time = 0;
    int minutes = 0;
    int seconds = 0;


    if (songCount > 0)
    {
        displayHeading();

        for (int i = 0; i < songCount; i++)
        {
        displayTextArea.append(songsArrayList.get(i).toString());
        appendLine();

        durationTemp = songsArrayList.get(i).getDuration();
        durationStr = durationTemp.replace(':','.');
        durationDbl = Double.parseDouble(durationStr);
        durationTotal = durationTotal + durationDbl;
        durationAvg = durationTotal / songCount;
        }

    time = (int)(100 * durationAvg);
    minutes = (int)(time/100);
    seconds = (int)(60 * (time%100));

    displayTextArea.append("average song duration: " + minutes + ":" + seconds);
    }

    else
    {
        displayError("No songs have been entered");
    }
}

标签: javatime

解决方案


3.33 分钟等于 199.8 秒,而 3:33 等于 213 秒。你不能(或不应该)只是替换:.

计算 durationAvg = durationTotal / songCount 没有意义;当你在 for 循环中时。做一次,在外面。


推荐阅读