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

本文关键字:整数 增加 一个 我希望 另一个 | 更新日期: 2023-09-27 18:05:53

我正在尝试用c#执行这个任务。

我有2个整数…int TotalScoreint ExtraLife

我想增加"ExtraLife"1每次总得分增加至少5?

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

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

你可以这样做

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

:

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

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