简体   繁体   中英

In c# I would like to increment an integer every time another integer increases by a set amount

I am trying to perform this task in c#.

I have 2 Integers... int TotalScore int ExtraLife

I would like to increase "ExtraLife" by 1 every time the TotalScore increases by at least 5?

Here is an example...

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.

    }

}

You can do something like this

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
}

try this:

public void Sample()
{
   int ExtraLife = 0;

   for (int TotalScore = 1; TotalScore <= 100; TotalScore++)
   {         
      if (TotalScore % 5 == 0)
          ExtraLife++;
   }
}
//ExtraLife = 20

UPDATE :

As example has been updated in the question, it seems that ExtraLife = TotalScore / 5; should give you right value. You don't need to increment ExtraLife integer:

 public void Example(int scored)
 {
    TotalScore += scored;    
    ExtraLife = TotalScore / 5;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM