2 回答

TA貢獻1868條經驗 獲得超4個贊
由于平均值的工作方式,您無法存儲平均分數。雖然您可以通過每次游戲結束時將計數器簡單地增加一個來計算用戶玩過的游戲,但是沒有分析形式來提高平均值。
但是,如果您存儲了游戲總數和總得分,那么您將能夠提高所需的所有指標。
class User
{
public int HighScore { get; private set; } = 0;
public double AverageScore =>
this.GamesPlayed > 0 ? this.TotalScore / (double)this.GamesPlayed : 0;
private int GamesPlayed { get; set; } = 0;
private int TotalScore { get; set; } = 0;
public void GameOver(int score)
{
this.HighScore = Math.Max(this.HighScore, score);
this.GamesPlayed += 1;
this.TotalScore += score;
}
}

TA貢獻1772條經驗 獲得超6個贊
您可以存儲平均值,然后在游戲結束后重新計算。這樣你就不需要存儲一個會導致溢出問題的值(totalscore)(遲早)。
class User
{
public int HighScore { get; private set; } = 0;
public double AverageScore { get; private set; } = 0;
private int GamesPlayed { get; set; } = 0;
public void GameOver(int score)
{
this.HighScore = Math.Max(this.HighScore, score);
// get the prev total score then increase with the current score and get the new average in the end (also increase the GamesPlayed)
this.AverageScore = ((this.AverageScore * this.GamesPlayed) + score) / ++this.GamesPlayed;
}
}
- 2 回答
- 0 關注
- 101 瀏覽
添加回答
舉報