reido113
reido113

Reputation: 113

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.

    }

}

Upvotes: 1

Views: 6412

Answers (2)

Hassan
Hassan

Reputation: 5430

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;
 }

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

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
}

Upvotes: 6

Related Questions