2 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
由于平均值的工作方式,您無(wú)法存儲(chǔ)平均分?jǐn)?shù)。雖然您可以通過(guò)每次游戲結(jié)束時(shí)將計(jì)數(shù)器簡(jiǎn)單地增加一個(gè)來(lái)計(jì)算用戶玩過(guò)的游戲,但是沒(méi)有分析形式來(lái)提高平均值。
但是,如果您存儲(chǔ)了游戲總數(shù)和總得分,那么您將能夠提高所需的所有指標(biāo)。
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貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以存儲(chǔ)平均值,然后在游戲結(jié)束后重新計(jì)算。這樣你就不需要存儲(chǔ)一個(gè)會(huì)導(dǎo)致溢出問(wèn)題的值(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 關(guān)注
- 98 瀏覽
添加回答
舉報(bào)