为了账号安全,请及时绑定邮箱和手机立即绑定

如何存储课堂平均分和最高分?

如何存储课堂平均分和最高分?

C#
萧十郎 2022-12-24 10:00:06
我不知道如何在我的 user.cs 类中存储玩家的平均分数、高分和完成游戏的平均时间。每当玩家完成我的一轮游戏时,平均分和最高分以及平均时间都必须在他们的标签中每次更新。我试过使用数组和数组列表,但我仍然不确定,因为它们似乎都不起作用。这是我的 user.cs 类:public class User    {        public string fname { get; set; } = "";        public string lname { get; set; } = "";        public string username { get; set; } = "";        public string password { get; set; } = "";        public User() { }        public User (string fname, string lname, string username, string password)        {            this.fname = fname;            this.lname = lname;            this.username = username;            this.password = password;        }    }我还需要在标签中显示用户名、用户名、高分、平均分和时间。格式应为双精度/浮点数。
查看完整描述

2 回答

?
MYYA

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;

    }

}


查看完整回答
反对 回复 2022-12-24
?
梦里花落0921

TA贡献1772条经验 获得超5个赞

您可以存储平均值,然后在游戏结束后重新计算。这样你就不需要存储一个会导致溢出问题的值(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;

    }

}


查看完整回答
反对 回复 2022-12-24
  • 2 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信