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

时间:2014-05-29 05:52:37

标签: c# integer

我正在尝试在c#中执行此任务。

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

我想增加&#34; ExtraLife&#34;每次总分数增加至少5?<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.

    }

}

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

试试这个:

public void Sample()
{
   int ExtraLife = 0;

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

<强>更新

由于示例已在问题中更新,ExtraLife = TotalScore / 5;似乎应该为您提供正确的价值。您不需要增加ExtraLife整数:

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