在c#中,我希望每当另一个整数增加一个设定量时增加一个整数

rei*_*113 1 c# integer

我试图在c#中执行此任务.

我有2个整数... int TotalScore int ExtraLife

每当TotalScore增加至少5时,我想将"ExtraLife"增加1?

这是一个例子......

public void Example(int scored)
{
    TotalScore += scored;

    if (TotalScore > 0 && TotalScore % 5 == 0)
    {
        ExtraLife++;

        // it seems that the ExtraLife will only increment if the
        // total score is a multiple of 5.
        // So if the TotalScore were 4 and 2 were passed
        // in as the argument, the ExtraLife will not increment.

    }

}
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 5

你可以做这样的事情

class Whatever
{
    private int extraLifeRemainder;

    private int totalScore;
    public int TotalScore
    {
        get { return totalScore; }
        set
        {
            int increment = (value - totalScore);
            DoIncrementExtraLife(increment);
            totalScore = value;
        }
    }

    public int ExtraLife { get; set; }

    private void DoIncrementExtraLife(int increment)
    {
        if (increment > 0)
        {
            this.extraLifeRemainder+= increment;
            int rem;
            int quotient = Math.DivRem(extraLifeRemainder, 5, out rem);
            this.ExtraLife += quotient;
            this.extraLifeRemainder= rem;
        }
    }
}

private static void Main()
{
    Whatever w = new Whatever();
    w.TotalScore += 8;
    w.TotalScore += 3;

    Console.WriteLine("TotalScore:{0}, ExtraLife:{1}", w.TotalScore, w.ExtraLife);
    //Prints 11 and 2
}
Run Code Online (Sandbox Code Playgroud)